Search is not available for this dataset
id
stringlengths 1
8
| text
stringlengths 72
9.81M
| addition_count
int64 0
10k
| commit_subject
stringlengths 0
3.7k
| deletion_count
int64 0
8.43k
| file_extension
stringlengths 0
32
| lang
stringlengths 1
94
| license
stringclasses 10
values | repo_name
stringlengths 9
59
|
---|---|---|---|---|---|---|---|---|
10071850 | <NME> README.md
<BEF> # [Split](https://libraries.io/rubygems/split)
[](http://badge.fury.io/rb/split)

[](https://codeclimate.com/github/splitrb/split)
[](https://codeclimate.com/github/splitrb/split/coverage)
[](https://github.com/RichardLitt/standard-readme)
[](https://www.codetriage.com/splitrb/split)
> 📈 The Rack Based A/B testing framework https://libraries.io/rubygems/split
Split is a rack based A/B testing framework designed to work with Rails, Sinatra or any other rack based app.
Split is heavily inspired by the [Abingo](https://github.com/ryanb/abingo) and [Vanity](https://github.com/assaf/vanity) Rails A/B testing plugins and [Resque](https://github.com/resque/resque) in its use of Redis.
Split is designed to be hacker friendly, allowing for maximum customisation and extensibility.
## Install
### Requirements
Split v4.0+ is currently tested with Ruby >= 2.5 and Rails >= 5.2.
If your project requires compatibility with Ruby 2.4.x or older Rails versions. You can try v3.0 or v0.8.0(for Ruby 1.9.3)
Split uses Redis as a datastore.
Split only supports Redis 4.0 or greater.
If you're on OS X, Homebrew is the simplest way to install Redis:
```bash
brew install redis
redis-server /usr/local/etc/redis.conf
```
You now have a Redis daemon running on port `6379`.
### Setup
```bash
gem install split
```
#### Rails
Adding `gem 'split'` to your Gemfile will autoload it when rails starts up, as long as you've configured Redis it will 'just work'.
#### Sinatra
To configure Sinatra with Split you need to enable sessions and mix in the helper methods. Add the following lines at the top of your Sinatra app:
```ruby
require 'split'
class MySinatraApp < Sinatra::Base
enable :sessions
helpers Split::Helper
get '/' do
...
end
```
## Usage
To begin your A/B test use the `ab_test` method, naming your experiment with the first argument and then the different alternatives which you wish to test on as the other arguments.
`ab_test` returns one of the alternatives, if a user has already seen that test they will get the same alternative as before, which you can use to split your code on.
It can be used to render different templates, show different text or any other case based logic.
`ab_finished` is used to make a completion of an experiment, or conversion.
Example: View
```erb
<% ab_test(:login_button, "/images/button1.jpg", "/images/button2.jpg") do |button_file| %>
<%= image_tag(button_file, alt: "Login!") %>
<% end %>
```
Example: Controller
```ruby
def register_new_user
# See what level of free points maximizes users' decision to buy replacement points.
@starter_points = ab_test(:new_user_free_points, '100', '200', '300')
end
```
Example: Conversion tracking (in a controller!)
```ruby
def buy_new_points
# some business logic
ab_finished(:new_user_free_points)
end
```
Example: Conversion tracking (in a view)
```erb
Thanks for signing up, dude! <% ab_finished(:signup_page_redesign) %>
```
You can find more examples, tutorials and guides on the [wiki](https://github.com/splitrb/split/wiki).
## Statistical Validity
Split has two options for you to use to determine which alternative is the best.
The first option (default on the dashboard) uses a z test (n>30) for the difference between your control and alternative conversion rates to calculate statistical significance. This test will tell you whether an alternative is better or worse than your control, but it will not distinguish between which alternative is the best in an experiment with multiple alternatives. Split will only tell you if your experiment is 90%, 95%, or 99% significant, and this test only works if you have more than 30 participants and 5 conversions for each branch.
As per this [blog post](https://www.evanmiller.org/how-not-to-run-an-ab-test.html) on the pitfalls of A/B testing, it is highly recommended that you determine your requisite sample size for each branch before running the experiment. Otherwise, you'll have an increased rate of false positives (experiments which show a significant effect where really there is none).
[Here](https://www.evanmiller.org/ab-testing/sample-size.html) is a sample size calculator for your convenience.
The second option uses simulations from a beta distribution to determine the probability that the given alternative is the winner compared to all other alternatives. You can view these probabilities by clicking on the drop-down menu labeled "Confidence." This option should be used when the experiment has more than just 1 control and 1 alternative. It can also be used for a simple, 2-alternative A/B test.
Calculating the beta-distribution simulations for a large number of experiments can be slow, so the results are cached. You can specify how often they should be recalculated (the default is once per day).
```ruby
Split.configure do |config|
config.winning_alternative_recalculation_interval = 3600 # 1 hour
end
```
## Extras
### Weighted alternatives
Perhaps you only want to show an alternative to 10% of your visitors because it is very experimental or not yet fully load tested.
To do this you can pass a weight with each alternative in the following ways:
```ruby
ab_test(:homepage_design, {'Old' => 18}, {'New' => 2})
ab_test(:homepage_design, 'Old', {'New' => 1.0/9})
ab_test(:homepage_design, {'Old' => 9}, 'New')
```
This will only show the new alternative to visitors 1 in 10 times, the default weight for an alternative is 1.
### Overriding alternatives
For development and testing, you may wish to force your app to always return an alternative.
You can do this by passing it as a parameter in the url.
If you have an experiment called `button_color` with alternatives called `red` and `blue` used on your homepage, a url such as:
http://myawesomesite.com?ab_test[button_color]=red
will always have red buttons. This won't be stored in your session or count towards to results, unless you set the `store_override` configuration option.
In the event you want to disable all tests without having to know the individual experiment names, add a `SPLIT_DISABLE` query parameter.
http://myawesomesite.com?SPLIT_DISABLE=true
It is not required to send `SPLIT_DISABLE=false` to activate Split.
### Rspec Helper
To aid testing with RSpec, write `spec/support/split_helper.rb` and call `use_ab_test(alternatives_by_experiment)` in your specs as instructed below:
```ruby
# Create a file with these contents at 'spec/support/split_helper.rb'
# and ensure it is `require`d in your rails_helper.rb or spec_helper.rb
module SplitHelper
# Force a specific experiment alternative to always be returned:
# use_ab_test(signup_form: "single_page")
#
# Force alternatives for multiple experiments:
# use_ab_test(signup_form: "single_page", pricing: "show_enterprise_prices")
#
def use_ab_test(alternatives_by_experiment)
allow_any_instance_of(Split::Helper).to receive(:ab_test) do |_receiver, experiment, &block|
variant = alternatives_by_experiment.fetch(experiment) { |key| raise "Unknown experiment '#{key}'" }
block.call(variant) unless block.nil?
variant
end
end
end
# Make the `use_ab_test` method available to all specs:
RSpec.configure do |config|
config.include SplitHelper
end
```
Now you can call `use_ab_test(alternatives_by_experiment)` in your specs, for example:
```ruby
it "registers using experimental signup" do
use_ab_test experiment_name: "alternative_name"
post "/signups"
...
end
```
### Starting experiments manually
By default new A/B tests will be active right after deployment. In case you would like to start new test a while after
the deploy, you can do it by setting the `start_manually` configuration option to `true`.
After choosing this option tests won't be started right after deploy, but after pressing the `Start` button in Split admin dashboard. If a test is deleted from the Split dashboard, then it can only be started after pressing the `Start` button whenever being re-initialized.
### Reset after completion
When a user completes a test their session is reset so that they may start the test again in the future.
To stop this behaviour you can pass the following option to the `ab_finished` method:
```ruby
ab_finished(:experiment_name, reset: false)
```
The user will then always see the alternative they started with.
Any old unfinished experiment key will be deleted from the user's data storage if the experiment had been removed or is over and a winner had been chosen. This allows a user to enroll into any new experiment in cases when the `allow_multiple_experiments` config option is set to `false`.
### Reset experiments manually
By default Split automatically resets the experiment whenever it detects the configuration for an experiment has changed (e.g. you call `ab_test` with different alternatives). You can prevent this by setting the option `reset_manually` to `true`.
You may want to do this when you want to change something, like the variants' names, the metadata about an experiment, etc. without resetting everything.
### Multiple experiments at once
By default Split will avoid users participating in multiple experiments at once. This means you are less likely to skew results by adding in more variation to your tests.
To stop this behaviour and allow users to participate in multiple experiments at once set the `allow_multiple_experiments` config option to true like so:
```ruby
Split.configure do |config|
config.allow_multiple_experiments = true
end
```
This will allow the user to participate in any number of experiments and belong to any alternative in each experiment. This has the possible downside of a variation in one experiment influencing the outcome of another.
To address this, setting the `allow_multiple_experiments` config option to 'control' like so:
```ruby
Split.configure do |config|
config.allow_multiple_experiments = 'control'
end
```
For this to work, each and every experiment you define must have an alternative named 'control'. This will allow the user to participate in multiple experiments as long as the user belongs to the alternative 'control' in each experiment. As soon as the user belongs to an alternative named something other than 'control' the user may not participate in any more experiments. Calling ab_test(<other experiments>) will always return the first alternative without adding the user to that experiment.
### Experiment Persistence
Split comes with three built-in persistence adapters for storing users and the alternatives they've been given for each experiment.
By default Split will store the tests for each user in the session.
You can optionally configure Split to use a cookie, Redis, or any custom adapter of your choosing.
#### Cookies
```ruby
Split.configure do |config|
config.persistence = :cookie
end
```
When using the cookie persistence, Split stores data into an anonymous tracking cookie named 'split', which expires in 1 year. To change that, set the `persistence_cookie_length` in the configuration (unit of time in seconds).
```ruby
Split.configure do |config|
config.persistence = :cookie
config.persistence_cookie_length = 2592000 # 30 days
end
```
The data stored consists of the experiment name and the variants the user is in. Example: { "experiment_name" => "variant_a" }
__Note:__ Using cookies depends on `ActionDispatch::Cookies` or any identical API
#### Redis
Using Redis will allow ab_users to persist across sessions or machines.
```ruby
Split.configure do |config|
config.persistence = Split::Persistence::RedisAdapter.with_config(lookup_by: -> (context) { context.current_user_id })
# Equivalent
# config.persistence = Split::Persistence::RedisAdapter.with_config(lookup_by: :current_user_id)
end
```
Options:
* `lookup_by`: method to invoke per request for uniquely identifying ab_users (mandatory configuration)
* `namespace`: separate namespace to store these persisted values (default "persistence")
* `expire_seconds`: sets TTL for user key. (if a user is in multiple experiments most recent update will reset TTL for all their assignments)
#### Dual Adapter
The Dual Adapter allows the use of different persistence adapters for logged-in and logged-out users. A common use case is to use Redis for logged-in users and Cookies for logged-out users.
```ruby
cookie_adapter = Split::Persistence::CookieAdapter
redis_adapter = Split::Persistence::RedisAdapter.with_config(
lookup_by: -> (context) { context.send(:current_user).try(:id) },
expire_seconds: 2592000)
Split.configure do |config|
config.persistence = Split::Persistence::DualAdapter.with_config(
logged_in: -> (context) { !context.send(:current_user).try(:id).nil? },
logged_in_adapter: redis_adapter,
logged_out_adapter: cookie_adapter)
config.persistence_cookie_length = 2592000 # 30 days
end
```
#### Custom Adapter
Your custom adapter needs to implement the same API as existing adapters.
See `Split::Persistence::CookieAdapter` or `Split::Persistence::SessionAdapter` for a starting point.
```ruby
Split.configure do |config|
config.persistence = YourCustomAdapterClass
end
```
### Trial Event Hooks
You can define methods that will be called at the same time as experiment
alternative participation and goal completion.
For example:
``` ruby
Split.configure do |config|
config.on_trial = :log_trial # run on every trial
config.on_trial_choose = :log_trial_choose # run on trials with new users only
config.on_trial_complete = :log_trial_complete
end
```
Set these attributes to a method name available in the same context as the
`ab_test` method. These methods should accept one argument, a `Trial` instance.
``` ruby
def log_trial(trial)
logger.info "experiment=%s alternative=%s user=%s" %
[ trial.experiment.name, trial.alternative, current_user.id ]
end
def log_trial_choose(trial)
logger.info "[new user] experiment=%s alternative=%s user=%s" %
[ trial.experiment.name, trial.alternative, current_user.id ]
end
def log_trial_complete(trial)
logger.info "experiment=%s alternative=%s user=%s complete=true" %
[ trial.experiment.name, trial.alternative, current_user.id ]
end
```
#### Views
If you are running `ab_test` from a view, you must define your event
hook callback as a
[helper_method](https://apidock.com/rails/AbstractController/Helpers/ClassMethods/helper_method)
in the controller:
``` ruby
helper_method :log_trial_choose
def log_trial_choose(trial)
logger.info "experiment=%s alternative=%s user=%s" %
[ trial.experiment.name, trial.alternative, current_user.id ]
end
```
### Experiment Hooks
You can assign a proc that will be called when an experiment is reset or deleted. You can use these hooks to call methods within your application to keep data related to experiments in sync with Split.
For example:
``` ruby
Split.configure do |config|
# after experiment reset or deleted
config.on_experiment_reset = -> (example) { # Do something on reset }
config.on_experiment_delete = -> (experiment) { # Do something else on delete }
# before experiment reset or deleted
config.on_before_experiment_reset = -> (example) { # Do something on reset }
config.on_before_experiment_delete = -> (experiment) { # Do something else on delete }
# after experiment winner had been set
config.on_experiment_winner_choose = -> (experiment) { # Do something on winner choose }
end
```
## Web Interface
Split comes with a Sinatra-based front end to get an overview of how your experiments are doing.
If you are running Rails 2: You can mount this inside your app using Rack::URLMap in your `config.ru`
```ruby
require 'split/dashboard'
run Rack::URLMap.new \
"/" => Your::App.new,
"/split" => Split::Dashboard.new
```
However, if you are using Rails 3 or higher: You can mount this inside your app routes by first adding this to the Gemfile:
```ruby
gem 'split', require: 'split/dashboard'
```
Then adding this to config/routes.rb
```ruby
mount Split::Dashboard, at: 'split'
```
You may want to password protect that page, you can do so with `Rack::Auth::Basic` (in your split initializer file)
```ruby
# Rails apps or apps that already depend on activesupport
Split::Dashboard.use Rack::Auth::Basic do |username, password|
# Protect against timing attacks:
# - Use & (do not use &&) so that it doesn't short circuit.
# - Use digests to stop length information leaking
ActiveSupport::SecurityUtils.secure_compare(::Digest::SHA256.hexdigest(username), ::Digest::SHA256.hexdigest(ENV["SPLIT_USERNAME"])) &
ActiveSupport::SecurityUtils.secure_compare(::Digest::SHA256.hexdigest(password), ::Digest::SHA256.hexdigest(ENV["SPLIT_PASSWORD"]))
end
# Apps without activesupport
Split::Dashboard.use Rack::Auth::Basic do |username, password|
# Protect against timing attacks:
# - Use & (do not use &&) so that it doesn't short circuit.
# - Use digests to stop length information leaking
Rack::Utils.secure_compare(::Digest::SHA256.hexdigest(username), ::Digest::SHA256.hexdigest(ENV["SPLIT_USERNAME"])) &
Rack::Utils.secure_compare(::Digest::SHA256.hexdigest(password), ::Digest::SHA256.hexdigest(ENV["SPLIT_PASSWORD"]))
end
```
You can even use Devise or any other Warden-based authentication method to authorize users. Just replace `mount Split::Dashboard, :at => 'split'` in `config/routes.rb` with the following:
```ruby
match "/split" => Split::Dashboard, anchor: false, via: [:get, :post, :delete], constraints: -> (request) do
request.env['warden'].authenticated? # are we authenticated?
request.env['warden'].authenticate! # authenticate if not already
# or even check any other condition such as request.env['warden'].user.is_admin?
end
```
More information on this [here](https://steve.dynedge.co.uk/2011/12/09/controlling-access-to-routes-and-rack-apps-in-rails-3-with-devise-and-warden/)
### Screenshot

## Configuration
You can override the default configuration options of Split like so:
```ruby
Split.configure do |config|
config.db_failover = true # handle Redis errors gracefully
config.db_failover_on_db_error = -> (error) { Rails.logger.error(error.message) }
config.allow_multiple_experiments = true
config.enabled = true
config.persistence = Split::Persistence::SessionAdapter
#config.start_manually = false ## new test will have to be started manually from the admin panel. default false
#config.reset_manually = false ## if true, it never resets the experiment data, even if the configuration changes
config.include_rails_helper = true
config.redis = "redis://custom.redis.url:6380"
end
```
Split looks for the Redis host in the environment variable `REDIS_URL` then
defaults to `redis://localhost:6379` if not specified by configure block.
On platforms like Heroku, Split will use the value of `REDIS_PROVIDER` to
determine which env variable key to use when retrieving the host config. This
defaults to `REDIS_URL`.
### Filtering
In most scenarios you don't want to have AB-Testing enabled for web spiders, robots or special groups of users.
Split provides functionality to filter this based on a predefined, extensible list of bots, IP-lists or custom exclude logic.
```ruby
Split.configure do |config|
# bot config
config.robot_regex = /my_custom_robot_regex/ # or
config.bots['newbot'] = "Description for bot with 'newbot' user agent, which will be added to config.robot_regex for exclusion"
# IP config
config.ignore_ip_addresses << '81.19.48.130' # or regex: /81\.19\.48\.[0-9]+/
# or provide your own filter functionality, the default is proc{ |request| is_robot? || is_ignored_ip_address? || is_preview? }
config.ignore_filter = -> (request) { CustomExcludeLogic.excludes?(request) }
end
```
### Experiment configuration
Instead of providing the experiment options inline, you can store them
in a hash. This hash can control your experiment's alternatives, weights,
algorithm and if the experiment resets once finished:
```ruby
Split.configure do |config|
config.experiments = {
my_first_experiment: {
alternatives: ["a", "b"],
resettable: false
},
:my_second_experiment => {
algorithm: 'Split::Algorithms::Whiplash',
alternatives: [
{ name: "a", percent: 67 },
{ name: "b", percent: 33 }
]
}
}
end
```
You can also store your experiments in a YAML file:
```ruby
Split.configure do |config|
config.experiments = YAML.load_file "config/experiments.yml"
end
```
You can then define the YAML file like:
```yaml
my_first_experiment:
alternatives:
- a
- b
my_second_experiment:
alternatives:
- name: a
percent: 67
- name: b
And our initializer:
```ruby
rails_root = ENV['RAILS_ROOT'] || File.dirname(__FILE__) + '/../..'
rails_env = ENV['RAILS_ENV'] || 'development'
split_config = YAML.load_file(rails_root + '/config/split.yml')
Split.redis = split_config[rails_env]
```
## Namespaces
```
and:
```ruby
ab_finished(:my_first_experiment)
```
You can also add meta data for each experiment, which is very useful when you need more than an alternative name to change behaviour:
```ruby
Split.configure do |config|
config.experiments = {
my_first_experiment: {
alternatives: ["a", "b"],
metadata: {
"a" => {"text" => "Have a fantastic day"},
"b" => {"text" => "Don't get hit by a bus"}
}
}
}
end
```
```yaml
my_first_experiment:
alternatives:
- a
- b
metadata:
a:
text: "Have a fantastic day"
b:
text: "Don't get hit by a bus"
```
This allows for some advanced experiment configuration using methods like:
```ruby
trial.alternative.name # => "a"
trial.metadata['text'] # => "Have a fantastic day"
```
or in views:
```erb
<% ab_test("my_first_experiment") do |alternative, meta| %>
<%= alternative %>
<small><%= meta['text'] %></small>
<% end %>
```
The keys used in meta data should be Strings
#### Metrics
You might wish to track generic metrics, such as conversions, and use
those to complete multiple different experiments without adding more to
your code. You can use the configuration hash to do this, thanks to
the `:metric` option.
```ruby
Split.configure do |config|
config.experiments = {
my_first_experiment: {
alternatives: ["a", "b"],
metric: :my_metric
}
}
end
```
Your code may then track a completion using the metric instead of
the experiment name:
```ruby
ab_finished(:my_metric)
```
You can also create a new metric by instantiating and saving a new Metric object.
```ruby
Split::Metric.new(:my_metric)
Split::Metric.save
```
#### Goals
You might wish to allow an experiment to have multiple, distinguishable goals.
The API to define goals for an experiment is this:
```ruby
ab_test({link_color: ["purchase", "refund"]}, "red", "blue")
```
or you can define them in a configuration file:
```ruby
Split.configure do |config|
config.experiments = {
link_color: {
alternatives: ["red", "blue"],
goals: ["purchase", "refund"]
}
}
end
```
To complete a goal conversion, you do it like:
```ruby
ab_finished(link_color: "purchase")
```
Note that if you pass additional options, that should be a separate hash:
```ruby
ab_finished({ link_color: "purchase" }, reset: false)
```
**NOTE:** This does not mean that a single experiment can complete more than one goal.
Once you finish one of the goals, the test is considered to be completed, and finishing the other goal will no longer register. (Assuming the test runs with `reset: false`.)
**Good Example**: Test if listing Plan A first result in more conversions to Plan A (goal: "plana_conversion") or Plan B (goal: "planb_conversion").
**Bad Example**: Test if button color increases conversion rate through multiple steps of a funnel. THIS WILL NOT WORK.
**Bad Example**: Test both how button color affects signup *and* how it affects login, at the same time. THIS WILL NOT WORK.
#### Combined Experiments
If you want to test how button color affects signup *and* how it affects login at the same time, use combined experiments.
Configure like so:
```ruby
Split.configuration.experiments = {
:button_color_experiment => {
:alternatives => ["blue", "green"],
:combined_experiments => ["button_color_on_signup", "button_color_on_login"]
}
}
```
Starting the combined test starts all combined experiments
```ruby
ab_combined_test(:button_color_experiment)
```
Finish each combined test as normal
```ruby
ab_finished(:button_color_on_login)
ab_finished(:button_color_on_signup)
```
**Additional Configuration**:
* Be sure to enable `allow_multiple_experiments`
* In Sinatra include the CombinedExperimentsHelper
```
helpers Split::CombinedExperimentsHelper
```
### DB failover solution
Due to the fact that Redis has no automatic failover mechanism, it's
possible to switch on the `db_failover` config option, so that `ab_test`
and `ab_finished` will not crash in case of a db failure. `ab_test` always
delivers alternative A (the first one) in that case.
It's also possible to set a `db_failover_on_db_error` callback (proc)
for example to log these errors via Rails.logger.
### Redis
You may want to change the Redis host and port Split connects to, or
set various other options at startup.
Split has a `redis` setter which can be given a string or a Redis
object. This means if you're already using Redis in your app, Split
can re-use the existing connection.
String: `Split.redis = 'redis://localhost:6379'`
Redis: `Split.redis = $redis`
For our rails app we have a `config/initializers/split.rb` file where
we load `config/split.yml` by hand and set the Redis information
appropriately.
Here's our `config/split.yml`:
```yml
development: redis://localhost:6379
test: redis://localhost:6379
staging: redis://redis1.example.com:6379
fi: redis://localhost:6379
production: redis://redis1.example.com:6379
```
And our initializer:
```ruby
split_config = YAML.load_file(Rails.root.join('config', 'split.yml'))
Split.redis = split_config[Rails.env]
```
### Redis Caching (v4.0+)
In some high-volume usage scenarios, Redis load can be incurred by repeated
fetches for fairly static data. Enabling caching will reduce this load.
```ruby
Split.configuration.cache = true
````
This currently caches:
- `Split::ExperimentCatalog.find`
- `Split::Experiment.start_time`
- `Split::Experiment.winner`
## Namespaces
If you're running multiple, separate instances of Split you may want
to namespace the keyspaces so they do not overlap. This is not unlike
the approach taken by many memcached clients.
This feature can be provided by the [redis-namespace](https://github.com/defunkt/redis-namespace)
library. To configure Split to use `Redis::Namespace`, do the following:
1. Add `redis-namespace` to your Gemfile:
```ruby
gem 'redis-namespace'
```
2. Configure `Split.redis` to use a `Redis::Namespace` instance (possible in an
initializer):
```ruby
redis = Redis.new(url: ENV['REDIS_URL']) # or whatever config you want
Split.redis = Redis::Namespace.new(:your_namespace, redis: redis)
```
## Outside of a Web Session
Split provides the Helper module to facilitate running experiments inside web sessions.
Alternatively, you can access the underlying Metric, Trial, Experiment and Alternative objects to
conduct experiments that are not tied to a web session.
```ruby
# create a new experiment
experiment = Split::ExperimentCatalog.find_or_create('color', 'red', 'blue')
# create a new trial
trial = Split::Trial.new(:experiment => experiment)
# run trial
trial.choose!
# get the result, returns either red or blue
trial.alternative.name
# if the goal has been achieved, increment the successful completions for this alternative.
if goal_achieved?
trial.complete!
end
```
## Algorithms
By default, Split ships with `Split::Algorithms::WeightedSample` that randomly selects from possible alternatives for a traditional a/b test.
It is possible to specify static weights to favor certain alternatives.
`Split::Algorithms::Whiplash` is an implementation of a [multi-armed bandit algorithm](http://stevehanov.ca/blog/index.php?id=132).
This algorithm will automatically weight the alternatives based on their relative performance,
choosing the better-performing ones more often as trials are completed.
`Split::Algorithms::BlockRandomization` is an algorithm that ensures equal
participation across all alternatives. This algorithm will choose the alternative
with the fewest participants. In the event of multiple minimum participant alternatives
(i.e. starting a new "Block") the algorithm will choose a random alternative from
those minimum participant alternatives.
Users may also write their own algorithms. The default algorithm may be specified globally in the configuration file, or on a per experiment basis using the experiments hash of the configuration file.
To change the algorithm globally for all experiments, use the following in your initializer:
```ruby
Split.configure do |config|
config.algorithm = Split::Algorithms::Whiplash
end
```
## Extensions
- [Split::Export](https://github.com/splitrb/split-export) - Easily export A/B test data out of Split.
- [Split::Analytics](https://github.com/splitrb/split-analytics) - Push test data to Google Analytics.
- [Split::Mongoid](https://github.com/MongoHQ/split-mongoid) - Store experiment data in mongoid (still uses redis).
- [Split::Cacheable](https://github.com/harrystech/split_cacheable) - Automatically create cache buckets per test.
- [Split::Counters](https://github.com/bernardkroes/split-counters) - Add counters per experiment and alternative.
- [Split::Cli](https://github.com/craigmcnamara/split-cli) - A CLI to trigger Split A/B tests.
## Screencast
Ryan bates has produced an excellent 10 minute screencast about split on the Railscasts site: [A/B Testing with Split](http://railscasts.com/episodes/331-a-b-testing-with-split)
## Blogposts
* [Recipe: A/B testing with KISSMetrics and the split gem](https://robots.thoughtbot.com/post/9595887299/recipe-a-b-testing-with-kissmetrics-and-the-split-gem)
* [Rails A/B testing with Split on Heroku](http://blog.nathanhumbert.com/2012/02/rails-ab-testing-with-split-on-heroku.html)
## Backers
Support us with a monthly donation and help us continue our activities. [[Become a backer](https://opencollective.com/split#backer)]
<a href="https://opencollective.com/split/backer/0/website" target="_blank"><img src="https://opencollective.com/split/backer/0/avatar.svg"></a>
<a href="https://opencollective.com/split/backer/1/website" target="_blank"><img src="https://opencollective.com/split/backer/1/avatar.svg"></a>
<a href="https://opencollective.com/split/backer/2/website" target="_blank"><img src="https://opencollective.com/split/backer/2/avatar.svg"></a>
<a href="https://opencollective.com/split/backer/3/website" target="_blank"><img src="https://opencollective.com/split/backer/3/avatar.svg"></a>
<a href="https://opencollective.com/split/backer/4/website" target="_blank"><img src="https://opencollective.com/split/backer/4/avatar.svg"></a>
<a href="https://opencollective.com/split/backer/5/website" target="_blank"><img src="https://opencollective.com/split/backer/5/avatar.svg"></a>
<a href="https://opencollective.com/split/backer/6/website" target="_blank"><img src="https://opencollective.com/split/backer/6/avatar.svg"></a>
<a href="https://opencollective.com/split/backer/7/website" target="_blank"><img src="https://opencollective.com/split/backer/7/avatar.svg"></a>
<a href="https://opencollective.com/split/backer/8/website" target="_blank"><img src="https://opencollective.com/split/backer/8/avatar.svg"></a>
<a href="https://opencollective.com/split/backer/9/website" target="_blank"><img src="https://opencollective.com/split/backer/9/avatar.svg"></a>
<a href="https://opencollective.com/split/backer/10/website" target="_blank"><img src="https://opencollective.com/split/backer/10/avatar.svg"></a>
<a href="https://opencollective.com/split/backer/11/website" target="_blank"><img src="https://opencollective.com/split/backer/11/avatar.svg"></a>
<a href="https://opencollective.com/split/backer/12/website" target="_blank"><img src="https://opencollective.com/split/backer/12/avatar.svg"></a>
<a href="https://opencollective.com/split/backer/13/website" target="_blank"><img src="https://opencollective.com/split/backer/13/avatar.svg"></a>
<a href="https://opencollective.com/split/backer/14/website" target="_blank"><img src="https://opencollective.com/split/backer/14/avatar.svg"></a>
<a href="https://opencollective.com/split/backer/15/website" target="_blank"><img src="https://opencollective.com/split/backer/15/avatar.svg"></a>
<a href="https://opencollective.com/split/backer/16/website" target="_blank"><img src="https://opencollective.com/split/backer/16/avatar.svg"></a>
<a href="https://opencollective.com/split/backer/17/website" target="_blank"><img src="https://opencollective.com/split/backer/17/avatar.svg"></a>
<a href="https://opencollective.com/split/backer/18/website" target="_blank"><img src="https://opencollective.com/split/backer/18/avatar.svg"></a>
<a href="https://opencollective.com/split/backer/19/website" target="_blank"><img src="https://opencollective.com/split/backer/19/avatar.svg"></a>
<a href="https://opencollective.com/split/backer/20/website" target="_blank"><img src="https://opencollective.com/split/backer/20/avatar.svg"></a>
<a href="https://opencollective.com/split/backer/21/website" target="_blank"><img src="https://opencollective.com/split/backer/21/avatar.svg"></a>
<a href="https://opencollective.com/split/backer/22/website" target="_blank"><img src="https://opencollective.com/split/backer/22/avatar.svg"></a>
<a href="https://opencollective.com/split/backer/23/website" target="_blank"><img src="https://opencollective.com/split/backer/23/avatar.svg"></a>
<a href="https://opencollective.com/split/backer/24/website" target="_blank"><img src="https://opencollective.com/split/backer/24/avatar.svg"></a>
<a href="https://opencollective.com/split/backer/25/website" target="_blank"><img src="https://opencollective.com/split/backer/25/avatar.svg"></a>
<a href="https://opencollective.com/split/backer/26/website" target="_blank"><img src="https://opencollective.com/split/backer/26/avatar.svg"></a>
<a href="https://opencollective.com/split/backer/27/website" target="_blank"><img src="https://opencollective.com/split/backer/27/avatar.svg"></a>
<a href="https://opencollective.com/split/backer/28/website" target="_blank"><img src="https://opencollective.com/split/backer/28/avatar.svg"></a>
<a href="https://opencollective.com/split/backer/29/website" target="_blank"><img src="https://opencollective.com/split/backer/29/avatar.svg"></a>
## 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/split#sponsor)]
<a href="https://opencollective.com/split/sponsor/0/website" target="_blank"><img src="https://opencollective.com/split/sponsor/0/avatar.svg"></a>
<a href="https://opencollective.com/split/sponsor/1/website" target="_blank"><img src="https://opencollective.com/split/sponsor/1/avatar.svg"></a>
<a href="https://opencollective.com/split/sponsor/2/website" target="_blank"><img src="https://opencollective.com/split/sponsor/2/avatar.svg"></a>
<a href="https://opencollective.com/split/sponsor/3/website" target="_blank"><img src="https://opencollective.com/split/sponsor/3/avatar.svg"></a>
<a href="https://opencollective.com/split/sponsor/4/website" target="_blank"><img src="https://opencollective.com/split/sponsor/4/avatar.svg"></a>
<a href="https://opencollective.com/split/sponsor/5/website" target="_blank"><img src="https://opencollective.com/split/sponsor/5/avatar.svg"></a>
<a href="https://opencollective.com/split/sponsor/6/website" target="_blank"><img src="https://opencollective.com/split/sponsor/6/avatar.svg"></a>
<a href="https://opencollective.com/split/sponsor/7/website" target="_blank"><img src="https://opencollective.com/split/sponsor/7/avatar.svg"></a>
<a href="https://opencollective.com/split/sponsor/8/website" target="_blank"><img src="https://opencollective.com/split/sponsor/8/avatar.svg"></a>
<a href="https://opencollective.com/split/sponsor/9/website" target="_blank"><img src="https://opencollective.com/split/sponsor/9/avatar.svg"></a>
<a href="https://opencollective.com/split/sponsor/10/website" target="_blank"><img src="https://opencollective.com/split/sponsor/10/avatar.svg"></a>
<a href="https://opencollective.com/split/sponsor/11/website" target="_blank"><img src="https://opencollective.com/split/sponsor/11/avatar.svg"></a>
<a href="https://opencollective.com/split/sponsor/12/website" target="_blank"><img src="https://opencollective.com/split/sponsor/12/avatar.svg"></a>
<a href="https://opencollective.com/split/sponsor/13/website" target="_blank"><img src="https://opencollective.com/split/sponsor/13/avatar.svg"></a>
<a href="https://opencollective.com/split/sponsor/14/website" target="_blank"><img src="https://opencollective.com/split/sponsor/14/avatar.svg"></a>
<a href="https://opencollective.com/split/sponsor/15/website" target="_blank"><img src="https://opencollective.com/split/sponsor/15/avatar.svg"></a>
<a href="https://opencollective.com/split/sponsor/16/website" target="_blank"><img src="https://opencollective.com/split/sponsor/16/avatar.svg"></a>
<a href="https://opencollective.com/split/sponsor/17/website" target="_blank"><img src="https://opencollective.com/split/sponsor/17/avatar.svg"></a>
<a href="https://opencollective.com/split/sponsor/18/website" target="_blank"><img src="https://opencollective.com/split/sponsor/18/avatar.svg"></a>
<a href="https://opencollective.com/split/sponsor/19/website" target="_blank"><img src="https://opencollective.com/split/sponsor/19/avatar.svg"></a>
<a href="https://opencollective.com/split/sponsor/20/website" target="_blank"><img src="https://opencollective.com/split/sponsor/20/avatar.svg"></a>
<a href="https://opencollective.com/split/sponsor/21/website" target="_blank"><img src="https://opencollective.com/split/sponsor/21/avatar.svg"></a>
<a href="https://opencollective.com/split/sponsor/22/website" target="_blank"><img src="https://opencollective.com/split/sponsor/22/avatar.svg"></a>
<a href="https://opencollective.com/split/sponsor/23/website" target="_blank"><img src="https://opencollective.com/split/sponsor/23/avatar.svg"></a>
<a href="https://opencollective.com/split/sponsor/24/website" target="_blank"><img src="https://opencollective.com/split/sponsor/24/avatar.svg"></a>
<a href="https://opencollective.com/split/sponsor/25/website" target="_blank"><img src="https://opencollective.com/split/sponsor/25/avatar.svg"></a>
<a href="https://opencollective.com/split/sponsor/26/website" target="_blank"><img src="https://opencollective.com/split/sponsor/26/avatar.svg"></a>
<a href="https://opencollective.com/split/sponsor/27/website" target="_blank"><img src="https://opencollective.com/split/sponsor/27/avatar.svg"></a>
<a href="https://opencollective.com/split/sponsor/28/website" target="_blank"><img src="https://opencollective.com/split/sponsor/28/avatar.svg"></a>
<a href="https://opencollective.com/split/sponsor/29/website" target="_blank"><img src="https://opencollective.com/split/sponsor/29/avatar.svg"></a>
## Contribute
Please do! Over 70 different people have contributed to the project, you can see them all here: https://github.com/splitrb/split/graphs/contributors.
### Development
The source code is hosted at [GitHub](https://github.com/splitrb/split).
Report issues and feature requests on [GitHub Issues](https://github.com/splitrb/split/issues).
You can find a discussion form on [Google Groups](https://groups.google.com/d/forum/split-ruby).
### Tests
Run the tests like this:
# Start a Redis server in another tab.
redis-server
bundle
rake spec
### A Note on Patches and Pull Requests
* Fork the project.
* Make your feature addition or bug fix.
* Add tests for it. This is important so I don't break it in a
future version unintentionally.
* Add documentation if necessary.
* Commit. Do not mess with the rakefile, version, or history.
(If you want to have your own version, that is fine. But bump the version in a commit by itself, which I can ignore when I pull.)
* Send a pull request. Bonus points for topic branches.
### Code of Conduct
Please note that this project is released with a [Contributor Code of Conduct](CODE_OF_CONDUCT.md). By participating in this project you agree to abide by its terms.
## Copyright
[MIT License](LICENSE) © 2019 [Andrew Nesbitt](https://github.com/andrew).
<MSG> Merge pull request #289 from byterussian/update-readme-rails-initializer
Update initializer code with Rails.root and Rails.env
<DFF> @@ -551,11 +551,8 @@ production: redis1.example.com:6379
And our initializer:
```ruby
-rails_root = ENV['RAILS_ROOT'] || File.dirname(__FILE__) + '/../..'
-rails_env = ENV['RAILS_ENV'] || 'development'
-
-split_config = YAML.load_file(rails_root + '/config/split.yml')
-Split.redis = split_config[rails_env]
+split_config = YAML.load_file(Rails.root.join('config', 'split.yml'))
+Split.redis = split_config[Rails.env]
```
## Namespaces
| 2 | Merge pull request #289 from byterussian/update-readme-rails-initializer | 5 | .md | md | mit | splitrb/split |
10071851 | <NME> trial_spec.rb
<BEF> # frozen_string_literal: true
require "spec_helper"
require "split/trial"
describe Split::Trial do
let(:user) { mock_user }
let(:alternatives) { ["basket", "cart"] }
let(:experiment) do
Split::Experiment.new("basket_text", alternatives: alternatives).save
end
it "should be initializeable" do
experiment = double("experiment")
alternative = double("alternative", kind_of?: Split::Alternative)
trial = Split::Trial.new(experiment: experiment, alternative: alternative)
expect(trial.experiment).to eq(experiment)
expect(trial.alternative).to eq(alternative)
end
describe "alternative" do
it "should use the alternative if specified" do
alternative = double("alternative", kind_of?: Split::Alternative)
trial = Split::Trial.new(experiment: double("experiment"),
alternative: alternative, user: user)
expect(trial).not_to receive(:choose)
expect(trial.alternative).to eq(alternative)
end
it "should load the alternative when the alternative name is set" do
experiment = Split::Experiment.new("basket_text", alternatives: ["basket", "cart"])
experiment.save
trial = Split::Trial.new(experiment: experiment, alternative: "basket")
expect(trial.alternative.name).to eq("basket")
end
end
describe "metadata" do
let(:metadata) { Hash[alternatives.map { |k| [k, "Metadata for #{k}"] }] }
let(:experiment) do
Split::Experiment.new("basket_text", alternatives: alternatives, metadata: metadata).save
end
it "has metadata on each trial" do
trial = Split::Trial.new(experiment: experiment, user: user, metadata: metadata["cart"],
override: "cart")
expect(trial.metadata).to eq(metadata["cart"])
end
it "has metadata on each trial from the experiment" do
trial = Split::Trial.new(experiment: experiment, user: user)
trial.choose!
expect(trial.metadata).to eq(metadata[trial.alternative.name])
expect(trial.metadata).to match(/#{trial.alternative.name}/)
end
end
describe "#choose!" do
let(:context) { double(on_trial_callback: "test callback") }
let(:trial) do
Split::Trial.new(user: user, experiment: experiment)
end
shared_examples_for "a trial with callbacks" do
it "does not run if on_trial callback is not respondable" do
Split.configuration.on_trial = :foo
allow(context).to receive(:respond_to?).with(:foo, true).and_return false
expect(context).to_not receive(:foo)
trial.choose! context
end
it "runs on_trial callback" do
Split.configuration.on_trial = :on_trial_callback
expect(context).to receive(:on_trial_callback)
trial.choose! context
end
it "does not run nil on_trial callback" do
Split.configuration.on_trial = nil
expect(context).not_to receive(:on_trial_callback)
trial.choose! context
end
end
def expect_alternative(trial, alternative_name)
3.times do
trial.choose! context
expect(alternative_name).to include(trial.alternative.name)
end
end
context "when override is present" do
let(:override) { "cart" }
let(:trial) do
Split::Trial.new(user: user, experiment: experiment, override: override)
end
it_behaves_like "a trial with callbacks"
it "picks the override" do
expect(experiment).to_not receive(:next_alternative)
expect_alternative(trial, override)
end
context "when alternative doesn't exist" do
let(:override) { nil }
it "falls back on next_alternative" do
expect(experiment).to receive(:next_alternative).and_call_original
expect_alternative(trial, alternatives)
end
end
end
context "when disabled option is true" do
let(:trial) do
Split::Trial.new(user: user, experiment: experiment, disabled: true)
end
it "picks the control", :aggregate_failures do
Split.configuration.on_trial = :on_trial_callback
expect(experiment).to_not receive(:next_alternative)
expect(context).not_to receive(:on_trial_callback)
expect_alternative(trial, "basket")
Split.configuration.on_trial = nil
end
end
context "when Split is globally disabled" do
it "picks the control and does not run on_trial callbacks", :aggregate_failures do
Split.configuration.enabled = false
Split.configuration.on_trial = :on_trial_callback
expect(experiment).to_not receive(:next_alternative)
expect(context).not_to receive(:on_trial_callback)
expect_alternative(trial, "basket")
Split.configuration.enabled = true
Split.configuration.on_trial = nil
end
end
context "when experiment has winner" do
let(:trial) do
Split::Trial.new(user: user, experiment: experiment)
end
it_behaves_like "a trial with callbacks"
it "picks the winner" do
experiment.winner = "cart"
expect(experiment).to_not receive(:next_alternative)
expect_alternative(trial, "cart")
end
end
context "when exclude is true" do
let(:trial) do
Split::Trial.new(user: user, experiment: experiment, exclude: true)
end
it_behaves_like "a trial with callbacks"
it "picks the control" do
expect(experiment).to_not receive(:next_alternative)
expect_alternative(trial, "basket")
end
end
context "when user is already participating" do
it_behaves_like "a trial with callbacks"
it "picks the same alternative" do
user[experiment.key] = "basket"
expect(experiment).to_not receive(:next_alternative)
expect_alternative(trial, "basket")
end
context "when alternative is not found" do
it "falls back on next_alternative" do
user[experiment.key] = "notfound"
expect(experiment).to receive(:next_alternative).and_call_original
expect_alternative(trial, alternatives)
end
end
end
context "when user is a new participant" do
it "picks a new alternative and runs on_trial_choose callback", :aggregate_failures do
Split.configuration.on_trial_choose = :on_trial_choose_callback
expect(experiment).to receive(:next_alternative).and_call_original
expect(context).to receive(:on_trial_choose_callback)
trial.choose! context
expect(trial.alternative.name).to_not be_empty
Split.configuration.on_trial_choose = nil
end
it "assigns user to an alternative" do
trial.choose! context
expect(alternatives).to include(user[experiment.name])
end
context "when cohorting is disabled" do
before(:each) { allow(experiment).to receive(:cohorting_disabled?).and_return(true) }
it "picks the control and does not run on_trial callbacks" do
Split.configuration.on_trial = :on_trial_callback
expect(experiment).to_not receive(:next_alternative)
expect(context).not_to receive(:on_trial_callback)
expect_alternative(trial, "basket")
Split.configuration.enabled = true
Split.configuration.on_trial = nil
end
it "user is not assigned an alternative" do
trial.choose! context
expect(user[experiment]).to eq(nil)
end
end
end
end
describe "#complete!" do
context "when there are no goals" do
let(:trial) { Split::Trial.new(user: user, experiment: experiment) }
it "should complete the trial" do
trial.choose!
old_completed_count = trial.alternative.completed_count
trial.complete!
Split.configuration.store_override = true
expect(user).to receive("[]=")
trial.choose!
end
it "does not store when store_override is false" do
it "increments the completed count corresponding to the goals" do
trial.choose!
old_completed_counts = goals.map { |goal| [goal, trial.alternative.completed_count(goal)] }.to_h
trial.complete!
goals.each { | goal | expect(trial.alternative.completed_count(goal)).to eq(old_completed_counts[goal] + 1) }
end
end
context "when there is 1 goal of type string" do
let(:goal) { "goal" }
let(:trial) { Split::Trial.new(user: user, experiment: experiment, goals: goal) }
it "increments the completed count corresponding to the goal" do
trial.choose!
old_completed_count = trial.alternative.completed_count(goal)
trial.complete!
expect(trial.alternative.completed_count(goal)).to eq(old_completed_count + 1)
end
end
end
describe "alternative recording" do
before(:each) { Split.configuration.store_override = false }
context "when override is present" do
it "stores when store_override is true" do
trial = Split::Trial.new(user: user, experiment: experiment, override: "basket")
Split.configuration.store_override = true
expect(user).to receive("[]=")
trial.choose!
expect(trial.alternative.participant_count).to eq(1)
end
it "does not store when store_override is false" do
trial = Split::Trial.new(user: user, experiment: experiment, override: "basket")
expect(user).to_not receive("[]=")
trial.choose!
end
end
context "when disabled is present" do
it "stores when store_override is true" do
trial = Split::Trial.new(user: user, experiment: experiment, disabled: true)
Split.configuration.store_override = true
expect(user).to receive("[]=")
trial.choose!
end
it "does not store when store_override is false" do
trial = Split::Trial.new(user: user, experiment: experiment, disabled: true)
expect(user).to_not receive("[]=")
trial.choose!
end
end
context "when exclude is present" do
it "does not store" do
trial = Split::Trial.new(user: user, experiment: experiment, exclude: true)
expect(user).to_not receive("[]=")
trial.choose!
end
end
context "when experiment has winner" do
let(:trial) do
experiment.winner = "cart"
Split::Trial.new(user: user, experiment: experiment)
end
it "does not store" do
expect(user).to_not receive("[]=")
trial.choose!
end
end
end
end
<MSG> Merge pull request #380 from spheric/master
increment participation if store override is true and no experiment key exists
<DFF> @@ -239,6 +239,7 @@ describe Split::Trial do
Split.configuration.store_override = true
expect(user).to receive("[]=")
trial.choose!
+ expect(trial.alternative.participant_count).to eq(1)
end
it "does not store when store_override is false" do
| 1 | Merge pull request #380 from spheric/master | 0 | .rb | rb | mit | splitrb/split |
10071852 | <NME> trial_spec.rb
<BEF> # frozen_string_literal: true
require "spec_helper"
require "split/trial"
describe Split::Trial do
let(:user) { mock_user }
let(:alternatives) { ["basket", "cart"] }
let(:experiment) do
Split::Experiment.new("basket_text", alternatives: alternatives).save
end
it "should be initializeable" do
experiment = double("experiment")
alternative = double("alternative", kind_of?: Split::Alternative)
trial = Split::Trial.new(experiment: experiment, alternative: alternative)
expect(trial.experiment).to eq(experiment)
expect(trial.alternative).to eq(alternative)
end
describe "alternative" do
it "should use the alternative if specified" do
alternative = double("alternative", kind_of?: Split::Alternative)
trial = Split::Trial.new(experiment: double("experiment"),
alternative: alternative, user: user)
expect(trial).not_to receive(:choose)
expect(trial.alternative).to eq(alternative)
end
it "should load the alternative when the alternative name is set" do
experiment = Split::Experiment.new("basket_text", alternatives: ["basket", "cart"])
experiment.save
trial = Split::Trial.new(experiment: experiment, alternative: "basket")
expect(trial.alternative.name).to eq("basket")
end
end
describe "metadata" do
let(:metadata) { Hash[alternatives.map { |k| [k, "Metadata for #{k}"] }] }
let(:experiment) do
Split::Experiment.new("basket_text", alternatives: alternatives, metadata: metadata).save
end
it "has metadata on each trial" do
trial = Split::Trial.new(experiment: experiment, user: user, metadata: metadata["cart"],
override: "cart")
expect(trial.metadata).to eq(metadata["cart"])
end
it "has metadata on each trial from the experiment" do
trial = Split::Trial.new(experiment: experiment, user: user)
trial.choose!
expect(trial.metadata).to eq(metadata[trial.alternative.name])
expect(trial.metadata).to match(/#{trial.alternative.name}/)
end
end
describe "#choose!" do
let(:context) { double(on_trial_callback: "test callback") }
let(:trial) do
Split::Trial.new(user: user, experiment: experiment)
end
shared_examples_for "a trial with callbacks" do
it "does not run if on_trial callback is not respondable" do
Split.configuration.on_trial = :foo
allow(context).to receive(:respond_to?).with(:foo, true).and_return false
expect(context).to_not receive(:foo)
trial.choose! context
end
it "runs on_trial callback" do
Split.configuration.on_trial = :on_trial_callback
expect(context).to receive(:on_trial_callback)
trial.choose! context
end
it "does not run nil on_trial callback" do
Split.configuration.on_trial = nil
expect(context).not_to receive(:on_trial_callback)
trial.choose! context
end
end
def expect_alternative(trial, alternative_name)
3.times do
trial.choose! context
expect(alternative_name).to include(trial.alternative.name)
end
end
context "when override is present" do
let(:override) { "cart" }
let(:trial) do
Split::Trial.new(user: user, experiment: experiment, override: override)
end
it_behaves_like "a trial with callbacks"
it "picks the override" do
expect(experiment).to_not receive(:next_alternative)
expect_alternative(trial, override)
end
context "when alternative doesn't exist" do
let(:override) { nil }
it "falls back on next_alternative" do
expect(experiment).to receive(:next_alternative).and_call_original
expect_alternative(trial, alternatives)
end
end
end
context "when disabled option is true" do
let(:trial) do
Split::Trial.new(user: user, experiment: experiment, disabled: true)
end
it "picks the control", :aggregate_failures do
Split.configuration.on_trial = :on_trial_callback
expect(experiment).to_not receive(:next_alternative)
expect(context).not_to receive(:on_trial_callback)
expect_alternative(trial, "basket")
Split.configuration.on_trial = nil
end
end
context "when Split is globally disabled" do
it "picks the control and does not run on_trial callbacks", :aggregate_failures do
Split.configuration.enabled = false
Split.configuration.on_trial = :on_trial_callback
expect(experiment).to_not receive(:next_alternative)
expect(context).not_to receive(:on_trial_callback)
expect_alternative(trial, "basket")
Split.configuration.enabled = true
Split.configuration.on_trial = nil
end
end
context "when experiment has winner" do
let(:trial) do
Split::Trial.new(user: user, experiment: experiment)
end
it_behaves_like "a trial with callbacks"
it "picks the winner" do
experiment.winner = "cart"
expect(experiment).to_not receive(:next_alternative)
expect_alternative(trial, "cart")
end
end
context "when exclude is true" do
let(:trial) do
Split::Trial.new(user: user, experiment: experiment, exclude: true)
end
it_behaves_like "a trial with callbacks"
it "picks the control" do
expect(experiment).to_not receive(:next_alternative)
expect_alternative(trial, "basket")
end
end
context "when user is already participating" do
it_behaves_like "a trial with callbacks"
it "picks the same alternative" do
user[experiment.key] = "basket"
expect(experiment).to_not receive(:next_alternative)
expect_alternative(trial, "basket")
end
context "when alternative is not found" do
it "falls back on next_alternative" do
user[experiment.key] = "notfound"
expect(experiment).to receive(:next_alternative).and_call_original
expect_alternative(trial, alternatives)
end
end
end
context "when user is a new participant" do
it "picks a new alternative and runs on_trial_choose callback", :aggregate_failures do
Split.configuration.on_trial_choose = :on_trial_choose_callback
expect(experiment).to receive(:next_alternative).and_call_original
expect(context).to receive(:on_trial_choose_callback)
trial.choose! context
expect(trial.alternative.name).to_not be_empty
Split.configuration.on_trial_choose = nil
end
it "assigns user to an alternative" do
trial.choose! context
expect(alternatives).to include(user[experiment.name])
end
context "when cohorting is disabled" do
before(:each) { allow(experiment).to receive(:cohorting_disabled?).and_return(true) }
it "picks the control and does not run on_trial callbacks" do
Split.configuration.on_trial = :on_trial_callback
expect(experiment).to_not receive(:next_alternative)
expect(context).not_to receive(:on_trial_callback)
expect_alternative(trial, "basket")
Split.configuration.enabled = true
Split.configuration.on_trial = nil
end
it "user is not assigned an alternative" do
trial.choose! context
expect(user[experiment]).to eq(nil)
end
end
end
end
describe "#complete!" do
context "when there are no goals" do
let(:trial) { Split::Trial.new(user: user, experiment: experiment) }
it "should complete the trial" do
trial.choose!
old_completed_count = trial.alternative.completed_count
trial.complete!
Split.configuration.store_override = true
expect(user).to receive("[]=")
trial.choose!
end
it "does not store when store_override is false" do
it "increments the completed count corresponding to the goals" do
trial.choose!
old_completed_counts = goals.map { |goal| [goal, trial.alternative.completed_count(goal)] }.to_h
trial.complete!
goals.each { | goal | expect(trial.alternative.completed_count(goal)).to eq(old_completed_counts[goal] + 1) }
end
end
context "when there is 1 goal of type string" do
let(:goal) { "goal" }
let(:trial) { Split::Trial.new(user: user, experiment: experiment, goals: goal) }
it "increments the completed count corresponding to the goal" do
trial.choose!
old_completed_count = trial.alternative.completed_count(goal)
trial.complete!
expect(trial.alternative.completed_count(goal)).to eq(old_completed_count + 1)
end
end
end
describe "alternative recording" do
before(:each) { Split.configuration.store_override = false }
context "when override is present" do
it "stores when store_override is true" do
trial = Split::Trial.new(user: user, experiment: experiment, override: "basket")
Split.configuration.store_override = true
expect(user).to receive("[]=")
trial.choose!
expect(trial.alternative.participant_count).to eq(1)
end
it "does not store when store_override is false" do
trial = Split::Trial.new(user: user, experiment: experiment, override: "basket")
expect(user).to_not receive("[]=")
trial.choose!
end
end
context "when disabled is present" do
it "stores when store_override is true" do
trial = Split::Trial.new(user: user, experiment: experiment, disabled: true)
Split.configuration.store_override = true
expect(user).to receive("[]=")
trial.choose!
end
it "does not store when store_override is false" do
trial = Split::Trial.new(user: user, experiment: experiment, disabled: true)
expect(user).to_not receive("[]=")
trial.choose!
end
end
context "when exclude is present" do
it "does not store" do
trial = Split::Trial.new(user: user, experiment: experiment, exclude: true)
expect(user).to_not receive("[]=")
trial.choose!
end
end
context "when experiment has winner" do
let(:trial) do
experiment.winner = "cart"
Split::Trial.new(user: user, experiment: experiment)
end
it "does not store" do
expect(user).to_not receive("[]=")
trial.choose!
end
end
end
end
<MSG> Merge pull request #380 from spheric/master
increment participation if store override is true and no experiment key exists
<DFF> @@ -239,6 +239,7 @@ describe Split::Trial do
Split.configuration.store_override = true
expect(user).to receive("[]=")
trial.choose!
+ expect(trial.alternative.participant_count).to eq(1)
end
it "does not store when store_override is false" do
| 1 | Merge pull request #380 from spheric/master | 0 | .rb | rb | mit | splitrb/split |
10071853 | <NME> trial_spec.rb
<BEF> # frozen_string_literal: true
require "spec_helper"
require "split/trial"
describe Split::Trial do
let(:user) { mock_user }
let(:alternatives) { ["basket", "cart"] }
let(:experiment) do
Split::Experiment.new("basket_text", alternatives: alternatives).save
end
it "should be initializeable" do
experiment = double("experiment")
alternative = double("alternative", kind_of?: Split::Alternative)
trial = Split::Trial.new(experiment: experiment, alternative: alternative)
expect(trial.experiment).to eq(experiment)
expect(trial.alternative).to eq(alternative)
end
describe "alternative" do
it "should use the alternative if specified" do
alternative = double("alternative", kind_of?: Split::Alternative)
trial = Split::Trial.new(experiment: double("experiment"),
alternative: alternative, user: user)
expect(trial).not_to receive(:choose)
expect(trial.alternative).to eq(alternative)
end
it "should load the alternative when the alternative name is set" do
experiment = Split::Experiment.new("basket_text", alternatives: ["basket", "cart"])
experiment.save
trial = Split::Trial.new(experiment: experiment, alternative: "basket")
expect(trial.alternative.name).to eq("basket")
end
end
describe "metadata" do
let(:metadata) { Hash[alternatives.map { |k| [k, "Metadata for #{k}"] }] }
let(:experiment) do
Split::Experiment.new("basket_text", alternatives: alternatives, metadata: metadata).save
end
it "has metadata on each trial" do
trial = Split::Trial.new(experiment: experiment, user: user, metadata: metadata["cart"],
override: "cart")
expect(trial.metadata).to eq(metadata["cart"])
end
it "has metadata on each trial from the experiment" do
trial = Split::Trial.new(experiment: experiment, user: user)
trial.choose!
expect(trial.metadata).to eq(metadata[trial.alternative.name])
expect(trial.metadata).to match(/#{trial.alternative.name}/)
end
end
describe "#choose!" do
let(:context) { double(on_trial_callback: "test callback") }
let(:trial) do
Split::Trial.new(user: user, experiment: experiment)
end
shared_examples_for "a trial with callbacks" do
it "does not run if on_trial callback is not respondable" do
Split.configuration.on_trial = :foo
allow(context).to receive(:respond_to?).with(:foo, true).and_return false
expect(context).to_not receive(:foo)
trial.choose! context
end
it "runs on_trial callback" do
Split.configuration.on_trial = :on_trial_callback
expect(context).to receive(:on_trial_callback)
trial.choose! context
end
it "does not run nil on_trial callback" do
Split.configuration.on_trial = nil
expect(context).not_to receive(:on_trial_callback)
trial.choose! context
end
end
def expect_alternative(trial, alternative_name)
3.times do
trial.choose! context
expect(alternative_name).to include(trial.alternative.name)
end
end
context "when override is present" do
let(:override) { "cart" }
let(:trial) do
Split::Trial.new(user: user, experiment: experiment, override: override)
end
it_behaves_like "a trial with callbacks"
it "picks the override" do
expect(experiment).to_not receive(:next_alternative)
expect_alternative(trial, override)
end
context "when alternative doesn't exist" do
let(:override) { nil }
it "falls back on next_alternative" do
expect(experiment).to receive(:next_alternative).and_call_original
expect_alternative(trial, alternatives)
end
end
end
context "when disabled option is true" do
let(:trial) do
Split::Trial.new(user: user, experiment: experiment, disabled: true)
end
it "picks the control", :aggregate_failures do
Split.configuration.on_trial = :on_trial_callback
expect(experiment).to_not receive(:next_alternative)
expect(context).not_to receive(:on_trial_callback)
expect_alternative(trial, "basket")
Split.configuration.on_trial = nil
end
end
context "when Split is globally disabled" do
it "picks the control and does not run on_trial callbacks", :aggregate_failures do
Split.configuration.enabled = false
Split.configuration.on_trial = :on_trial_callback
expect(experiment).to_not receive(:next_alternative)
expect(context).not_to receive(:on_trial_callback)
expect_alternative(trial, "basket")
Split.configuration.enabled = true
Split.configuration.on_trial = nil
end
end
context "when experiment has winner" do
let(:trial) do
Split::Trial.new(user: user, experiment: experiment)
end
it_behaves_like "a trial with callbacks"
it "picks the winner" do
experiment.winner = "cart"
expect(experiment).to_not receive(:next_alternative)
expect_alternative(trial, "cart")
end
end
context "when exclude is true" do
let(:trial) do
Split::Trial.new(user: user, experiment: experiment, exclude: true)
end
it_behaves_like "a trial with callbacks"
it "picks the control" do
expect(experiment).to_not receive(:next_alternative)
expect_alternative(trial, "basket")
end
end
context "when user is already participating" do
it_behaves_like "a trial with callbacks"
it "picks the same alternative" do
user[experiment.key] = "basket"
expect(experiment).to_not receive(:next_alternative)
expect_alternative(trial, "basket")
end
context "when alternative is not found" do
it "falls back on next_alternative" do
user[experiment.key] = "notfound"
expect(experiment).to receive(:next_alternative).and_call_original
expect_alternative(trial, alternatives)
end
end
end
context "when user is a new participant" do
it "picks a new alternative and runs on_trial_choose callback", :aggregate_failures do
Split.configuration.on_trial_choose = :on_trial_choose_callback
expect(experiment).to receive(:next_alternative).and_call_original
expect(context).to receive(:on_trial_choose_callback)
trial.choose! context
expect(trial.alternative.name).to_not be_empty
Split.configuration.on_trial_choose = nil
end
it "assigns user to an alternative" do
trial.choose! context
expect(alternatives).to include(user[experiment.name])
end
context "when cohorting is disabled" do
before(:each) { allow(experiment).to receive(:cohorting_disabled?).and_return(true) }
it "picks the control and does not run on_trial callbacks" do
Split.configuration.on_trial = :on_trial_callback
expect(experiment).to_not receive(:next_alternative)
expect(context).not_to receive(:on_trial_callback)
expect_alternative(trial, "basket")
Split.configuration.enabled = true
Split.configuration.on_trial = nil
end
it "user is not assigned an alternative" do
trial.choose! context
expect(user[experiment]).to eq(nil)
end
end
end
end
describe "#complete!" do
context "when there are no goals" do
let(:trial) { Split::Trial.new(user: user, experiment: experiment) }
it "should complete the trial" do
trial.choose!
old_completed_count = trial.alternative.completed_count
trial.complete!
Split.configuration.store_override = true
expect(user).to receive("[]=")
trial.choose!
end
it "does not store when store_override is false" do
it "increments the completed count corresponding to the goals" do
trial.choose!
old_completed_counts = goals.map { |goal| [goal, trial.alternative.completed_count(goal)] }.to_h
trial.complete!
goals.each { | goal | expect(trial.alternative.completed_count(goal)).to eq(old_completed_counts[goal] + 1) }
end
end
context "when there is 1 goal of type string" do
let(:goal) { "goal" }
let(:trial) { Split::Trial.new(user: user, experiment: experiment, goals: goal) }
it "increments the completed count corresponding to the goal" do
trial.choose!
old_completed_count = trial.alternative.completed_count(goal)
trial.complete!
expect(trial.alternative.completed_count(goal)).to eq(old_completed_count + 1)
end
end
end
describe "alternative recording" do
before(:each) { Split.configuration.store_override = false }
context "when override is present" do
it "stores when store_override is true" do
trial = Split::Trial.new(user: user, experiment: experiment, override: "basket")
Split.configuration.store_override = true
expect(user).to receive("[]=")
trial.choose!
expect(trial.alternative.participant_count).to eq(1)
end
it "does not store when store_override is false" do
trial = Split::Trial.new(user: user, experiment: experiment, override: "basket")
expect(user).to_not receive("[]=")
trial.choose!
end
end
context "when disabled is present" do
it "stores when store_override is true" do
trial = Split::Trial.new(user: user, experiment: experiment, disabled: true)
Split.configuration.store_override = true
expect(user).to receive("[]=")
trial.choose!
end
it "does not store when store_override is false" do
trial = Split::Trial.new(user: user, experiment: experiment, disabled: true)
expect(user).to_not receive("[]=")
trial.choose!
end
end
context "when exclude is present" do
it "does not store" do
trial = Split::Trial.new(user: user, experiment: experiment, exclude: true)
expect(user).to_not receive("[]=")
trial.choose!
end
end
context "when experiment has winner" do
let(:trial) do
experiment.winner = "cart"
Split::Trial.new(user: user, experiment: experiment)
end
it "does not store" do
expect(user).to_not receive("[]=")
trial.choose!
end
end
end
end
<MSG> Merge pull request #380 from spheric/master
increment participation if store override is true and no experiment key exists
<DFF> @@ -239,6 +239,7 @@ describe Split::Trial do
Split.configuration.store_override = true
expect(user).to receive("[]=")
trial.choose!
+ expect(trial.alternative.participant_count).to eq(1)
end
it "does not store when store_override is false" do
| 1 | Merge pull request #380 from spheric/master | 0 | .rb | rb | mit | splitrb/split |
10071854 | <NME> helper_spec.rb
<BEF> # frozen_string_literal: true
require "spec_helper"
# TODO change some of these tests to use Rack::Test
describe Split::Helper do
include Split::Helper
let(:experiment) {
Split::ExperimentCatalog.find_or_create("link_color", "blue", "red")
}
describe "ab_test" do
it "should not raise an error when passed strings for alternatives" do
expect { ab_test("xyz", "1", "2", "3") }.not_to raise_error
end
it "should not raise an error when passed an array for alternatives" do
expect { ab_test("xyz", ["1", "2", "3"]) }.not_to raise_error
end
it "should raise the appropriate error when passed integers for alternatives" do
expect { ab_test("xyz", 1, 2, 3) }.to raise_error(ArgumentError)
end
it "should raise the appropriate error when passed symbols for alternatives" do
expect { ab_test("xyz", :a, :b, :c) }.to raise_error(ArgumentError)
end
it "should not raise error when passed an array for goals" do
expect { ab_test({ "link_color" => ["purchase", "refund"] }, "blue", "red") }.not_to raise_error
end
it "should not raise error when passed just one goal" do
expect { ab_test({ "link_color" => "purchase" }, "blue", "red") }.not_to raise_error
end
it "raises an appropriate error when processing combined expirements" do
Split.configuration.experiments = {
combined_exp_1: {
alternatives: [ { name: "control", percent: 50 }, { name: "test-alt", percent: 50 } ],
metric: :my_metric,
combined_experiments: [:combined_exp_1_sub_1]
}
}
Split::ExperimentCatalog.find_or_create("combined_exp_1")
expect { ab_test("combined_exp_1") }.to raise_error(Split::InvalidExperimentsFormatError)
end
it "should assign a random alternative to a new user when there are an equal number of alternatives assigned" do
ab_test("link_color", "blue", "red")
expect(["red", "blue"]).to include(ab_user["link_color"])
end
it "should increment the participation counter after assignment to a new user" do
previous_red_count = Split::Alternative.new("red", "link_color").participant_count
previous_blue_count = Split::Alternative.new("blue", "link_color").participant_count
ab_test("link_color", "blue", "red")
new_red_count = Split::Alternative.new("red", "link_color").participant_count
new_blue_count = Split::Alternative.new("blue", "link_color").participant_count
expect((new_red_count + new_blue_count)).to eq(previous_red_count + previous_blue_count + 1)
end
it "should not increment the counter for an experiment that the user is not participating in" do
ab_test("link_color", "blue", "red")
e = Split::ExperimentCatalog.find_or_create("button_size", "small", "big")
expect {
# User shouldn't participate in this second experiment
ab_test("button_size", "small", "big")
}.not_to change { e.participant_count }
end
it "should not increment the counter for an ended experiment" do
e = Split::ExperimentCatalog.find_or_create("button_size", "small", "big")
e.winner = "small"
expect {
a = ab_test("button_size", "small", "big")
expect(a).to eq("small")
}.not_to change { e.participant_count }
end
it "should not increment the counter for an not started experiment" do
expect(Split.configuration).to receive(:start_manually).and_return(true)
e = Split::ExperimentCatalog.find_or_create("button_size", "small", "big")
expect {
a = ab_test("button_size", "small", "big")
expect(a).to eq("small")
}.not_to change { e.participant_count }
end
it "should return the given alternative for an existing user" do
expect(ab_test("link_color", "blue", "red")).to eq ab_test("link_color", "blue", "red")
end
it "should always return the winner if one is present" do
experiment.winner = "orange"
expect(ab_test("link_color", "blue", "red")).to eq("orange")
end
it "should allow the alternative to be forced by passing it in the params" do
# ?ab_test[link_color]=blue
@params = { "ab_test" => { "link_color" => "blue" } }
alternative = ab_test("link_color", "blue", "red")
expect(alternative).to eq("blue")
alternative = ab_test("link_color", { "blue" => 1 }, "red" => 5)
expect(alternative).to eq("blue")
@params = { "ab_test" => { "link_color" => "red" } }
alternative = ab_test("link_color", "blue", "red")
expect(alternative).to eq("red")
alternative = ab_test("link_color", { "blue" => 5 }, "red" => 1)
expect(alternative).to eq("red")
end
it "should not allow an arbitrary alternative" do
@params = { "ab_test" => { "link_color" => "pink" } }
alternative = ab_test("link_color", "blue")
expect(alternative).to eq("blue")
end
it "should not store the split when a param forced alternative" do
@params = { "ab_test" => { "link_color" => "blue" } }
expect(ab_user).not_to receive(:[]=)
ab_test("link_color", "blue", "red")
end
it "SPLIT_DISABLE query parameter should also force the alternative (uses control)" do
@params = { "SPLIT_DISABLE" => "true" }
alternative = ab_test("link_color", "blue", "red")
expect(alternative).to eq("blue")
alternative = ab_test("link_color", { "blue" => 1 }, "red" => 5)
expect(alternative).to eq("blue")
alternative = ab_test("link_color", "red", "blue")
expect(alternative).to eq("red")
alternative = ab_test("link_color", { "red" => 5 }, "blue" => 1)
expect(alternative).to eq("red")
end
it "should not store the split when Split generically disabled" do
@params = { "SPLIT_DISABLE" => "true" }
expect(ab_user).not_to receive(:[]=)
ab_test("link_color", "blue", "red")
end
context "when store_override is set" do
before { Split.configuration.store_override = true }
it "should store the forced alternative" do
@params = { "ab_test" => { "link_color" => "blue" } }
expect(ab_user).to receive(:[]=).with("link_color", "blue")
ab_test("link_color", "blue", "red")
end
end
context "when on_trial_choose is set" do
before { Split.configuration.on_trial_choose = :some_method }
it "should call the method" do
expect(self).to receive(:some_method)
ab_test("link_color", "blue", "red")
end
end
it "should allow passing a block" do
alt = ab_test("link_color", "blue", "red")
ret = ab_test("link_color", "blue", "red") { |alternative| "shared/#{alternative}" }
expect(ret).to eq("shared/#{alt}")
end
session[:split] = nil
lambda { finished('some_experiment_not_started_by_the_user') }.should_not raise_exception
end
end
describe 'conversions' do
it "should only let a user participate in one experiment at a time" do
link_color = ab_test("link_color", "blue", "red")
ab_test("button_size", "small", "big")
expect(ab_user["link_color"]).to eq(link_color)
big = Split::Alternative.new("big", "button_size")
expect(big.participant_count).to eq(0)
small = Split::Alternative.new("small", "button_size")
expect(small.participant_count).to eq(0)
end
it "should let a user participate in many experiment with allow_multiple_experiments option" do
Split.configure do |config|
config.allow_multiple_experiments = true
end
link_color = ab_test("link_color", "blue", "red")
button_size = ab_test("button_size", "small", "big")
expect(ab_user["link_color"]).to eq(link_color)
expect(ab_user["button_size"]).to eq(button_size)
button_size_alt = Split::Alternative.new(button_size, "button_size")
expect(button_size_alt.participant_count).to eq(1)
end
context "with allow_multiple_experiments = 'control'" do
it "should let a user participate in many experiment with one non-'control' alternative" do
Split.configure do |config|
config.allow_multiple_experiments = "control"
end
groups = 100.times.map do |n|
ab_test("test#{n}".to_sym, { "control" => (100 - n) }, { "test#{n}-alt" => n })
end
experiments = ab_user.active_experiments
expect(experiments.size).to be > 1
count_control = experiments.values.count { |g| g == "control" }
expect(count_control).to eq(experiments.size - 1)
count_alts = groups.count { |g| g != "control" }
expect(count_alts).to eq(1)
end
context "when user already has experiment" do
let(:mock_user) { Split::User.new(self, { "test_0" => "test-alt" }) }
before do
Split.configure do |config|
config.allow_multiple_experiments = "control"
end
Split::ExperimentCatalog.find_or_initialize("test_0", "control", "test-alt").save
Split::ExperimentCatalog.find_or_initialize("test_1", "control", "test-alt").save
end
it "should restore previously selected alternative" do
expect(ab_user.active_experiments.size).to eq 1
expect(ab_test(:test_0, { "control" => 100 }, { "test-alt" => 1 })).to eq "test-alt"
expect(ab_test(:test_0, { "control" => 1 }, { "test-alt" => 100 })).to eq "test-alt"
end
it "should select the correct alternatives after experiment resets" do
experiment = Split::ExperimentCatalog.find(:test_0)
experiment.reset
mock_user[experiment.key] = "test-alt"
expect(ab_user.active_experiments.size).to eq 1
expect(ab_test(:test_0, { "control" => 100 }, { "test-alt" => 1 })).to eq "test-alt"
expect(ab_test(:test_0, { "control" => 0 }, { "test-alt" => 100 })).to eq "test-alt"
end
it "lets override existing choice" do
pending "this requires user store reset on first call not depending on whelther it is current trial"
@params = { "ab_test" => { "test_1" => "test-alt" } }
expect(ab_test(:test_0, { "control" => 0 }, { "test-alt" => 100 })).to eq "control"
expect(ab_test(:test_1, { "control" => 100 }, { "test-alt" => 1 })).to eq "test-alt"
end
end
end
it "should not over-write a finished key when an experiment is on a later version" do
experiment.increment_version
ab_user = { experiment.key => "blue", experiment.finished_key => true }
finished_session = ab_user.dup
ab_test("link_color", "blue", "red")
expect(ab_user).to eq(finished_session)
end
end
describe "metadata" do
context "is defined" do
before do
Split.configuration.experiments = {
my_experiment: {
alternatives: ["one", "two"],
resettable: false,
metadata: { "one" => "Meta1", "two" => "Meta2" }
}
}
end
it "should be passed to helper block" do
@params = { "ab_test" => { "my_experiment" => "two" } }
expect(ab_test("my_experiment")).to eq "two"
expect(ab_test("my_experiment") do |alternative, meta|
meta
end).to eq("Meta2")
end
it "should pass control metadata helper block if library disabled" do
Split.configure do |config|
config.enabled = false
end
expect(ab_test("my_experiment")).to eq "one"
expect(ab_test("my_experiment") do |_, meta|
meta
end).to eq("Meta1")
end
end
context "is not defined" do
before do
Split.configuration.experiments = {
my_experiment: {
alternatives: ["one", "two"],
resettable: false,
metadata: nil
}
}
end
it "should be passed to helper block" do
expect(ab_test("my_experiment") do |alternative, meta|
meta
end).to eq({})
end
it "should pass control metadata helper block if library disabled" do
Split.configure do |config|
config.enabled = false
end
expect(ab_test("my_experiment") do |_, meta|
meta
end).to eq({})
end
end
end
describe "ab_finished" do
context "for an experiment that the user participates in" do
before(:each) do
@experiment_name = "link_color"
@alternatives = ["blue", "red"]
@experiment = Split::ExperimentCatalog.find_or_create(@experiment_name, *@alternatives)
@alternative_name = ab_test(@experiment_name, *@alternatives)
@previous_completion_count = Split::Alternative.new(@alternative_name, @experiment_name).completed_count
end
it "should increment the counter for the completed alternative" do
ab_finished(@experiment_name)
new_completion_count = Split::Alternative.new(@alternative_name, @experiment_name).completed_count
expect(new_completion_count).to eq(@previous_completion_count + 1)
end
it "should set experiment's finished key if reset is false" do
ab_finished(@experiment_name, { reset: false })
expect(ab_user[@experiment.key]).to eq(@alternative_name)
expect(ab_user[@experiment.finished_key]).to eq(true)
end
it "should not increment the counter if reset is false and the experiment has been already finished" do
2.times { ab_finished(@experiment_name, { reset: false }) }
new_completion_count = Split::Alternative.new(@alternative_name, @experiment_name).completed_count
expect(new_completion_count).to eq(@previous_completion_count + 1)
end
it "should not increment the counter for an ended experiment" do
e = Split::ExperimentCatalog.find_or_create("button_size", "small", "big")
e.winner = "small"
a = ab_test("button_size", "small", "big")
expect(a).to eq("small")
expect {
ab_finished("button_size")
}.not_to change { Split::Alternative.new(a, "button_size").completed_count }
end
it "should clear out the user's participation from their session" do
expect(ab_user[@experiment.key]).to eq(@alternative_name)
ab_finished(@experiment_name)
expect(ab_user.keys).to be_empty
end
it "should not clear out the users session if reset is false" do
expect(ab_user[@experiment.key]).to eq(@alternative_name)
ab_finished(@experiment_name, { reset: false })
expect(ab_user[@experiment.key]).to eq(@alternative_name)
expect(ab_user[@experiment.finished_key]).to eq(true)
end
it "should reset the users session when experiment is not versioned" do
expect(ab_user[@experiment.key]).to eq(@alternative_name)
ab_finished(@experiment_name)
expect(ab_user.keys).to be_empty
end
it "should reset the users session when experiment is versioned" do
@experiment.increment_version
@alternative_name = ab_test(@experiment_name, *@alternatives)
expect(ab_user[@experiment.key]).to eq(@alternative_name)
ab_finished(@experiment_name)
expect(ab_user.keys).to be_empty
end
context "when on_trial_complete is set" do
before { Split.configuration.on_trial_complete = :some_method }
it "should call the method" do
expect(self).to receive(:some_method)
ab_finished(@experiment_name)
end
it "should not call the method without alternative" do
ab_user[@experiment.key] = nil
expect(self).not_to receive(:some_method)
ab_finished(@experiment_name)
end
end
end
context "for an experiment that the user is excluded from" do
before do
alternative = ab_test("link_color", "blue", "red")
expect(Split::Alternative.new(alternative, "link_color").participant_count).to eq(1)
alternative = ab_test("button_size", "small", "big")
expect(Split::Alternative.new(alternative, "button_size").participant_count).to eq(0)
end
it "should not increment the completed counter" do
# So, user should be participating in the link_color experiment and
# receive the control for button_size. As the user is not participating in
# the button size experiment, finishing it should not increase the
# completion count for that alternative.
expect {
ab_finished("button_size")
}.not_to change { Split::Alternative.new("small", "button_size").completed_count }
end
end
context "for an experiment that the user does not participate in" do
before do
Split::ExperimentCatalog.find_or_create(:not_started_experiment, "control", "alt")
end
it "should not raise an exception" do
expect { ab_finished(:not_started_experiment) }.not_to raise_exception
end
it "should not change the user state when reset is false" do
expect { ab_finished(:not_started_experiment, reset: false) }.not_to change { ab_user.keys }.from([])
end
it "should not change the user state when reset is true" do
expect(self).not_to receive(:reset!)
ab_finished(:not_started_experiment)
end
it "should not increment the completed counter" do
ab_finished(:not_started_experiment)
expect(Split::Alternative.new("control", :not_started_experiment).completed_count).to eq(0)
expect(Split::Alternative.new("alt", :not_started_experiment).completed_count).to eq(0)
end
end
end
context "finished with config" do
it "passes reset option" do
Split.configuration.experiments = {
my_experiment: {
alternatives: ["one", "two"],
resettable: false,
}
}
alternative = ab_test(:my_experiment)
experiment = Split::ExperimentCatalog.find :my_experiment
ab_finished :my_experiment
expect(ab_user[experiment.key]).to eq(alternative)
expect(ab_user[experiment.finished_key]).to eq(true)
end
end
context "finished with metric name" do
before { Split.configuration.experiments = {} }
before { expect(Split::Alternative).to receive(:new).at_least(1).times.and_call_original }
def should_finish_experiment(experiment_name, should_finish = true)
alts = Split.configuration.experiments[experiment_name][:alternatives]
experiment = Split::ExperimentCatalog.find_or_create(experiment_name, *alts)
alt_name = ab_user[experiment.key] = alts.first
alt = double("alternative")
expect(alt).to receive(:name).at_most(1).times.and_return(alt_name)
expect(Split::Alternative).to receive(:new).at_most(1).times.with(alt_name, experiment_name.to_s).and_return(alt)
if should_finish
expect(alt).to receive(:increment_completion).at_most(1).times
else
expect(alt).not_to receive(:increment_completion)
end
end
it "completes the test" do
Split.configuration.experiments[:my_experiment] = {
alternatives: [ "control_opt", "other_opt" ],
metric: :my_metric
}
should_finish_experiment :my_experiment
ab_finished :my_metric
end
it "completes all relevant tests" do
Split.configuration.experiments = {
exp_1: {
alternatives: [ "1-1", "1-2" ],
metric: :my_metric
},
exp_2: {
alternatives: [ "2-1", "2-2" ],
metric: :another_metric
},
exp_3: {
alternatives: [ "3-1", "3-2" ],
metric: :my_metric
},
}
should_finish_experiment :exp_1
should_finish_experiment :exp_2, false
should_finish_experiment :exp_3
ab_finished :my_metric
end
it "passes reset option" do
Split.configuration.experiments = {
my_exp: {
alternatives: ["one", "two"],
metric: :my_metric,
resettable: false,
}
}
alternative_name = ab_test(:my_exp)
exp = Split::ExperimentCatalog.find :my_exp
ab_finished :my_metric
expect(ab_user[exp.key]).to eq(alternative_name)
expect(ab_user[exp.finished_key]).to be_truthy
end
it "passes through options" do
Split.configuration.experiments = {
my_exp: {
alternatives: ["one", "two"],
metric: :my_metric,
}
}
alternative_name = ab_test(:my_exp)
exp = Split::ExperimentCatalog.find :my_exp
ab_finished :my_metric, reset: false
expect(ab_user[exp.key]).to eq(alternative_name)
expect(ab_user[exp.finished_key]).to be_truthy
end
end
describe "conversions" do
it "should return a conversion rate for an alternative" do
alternative_name = ab_test("link_color", "blue", "red")
previous_convertion_rate = Split::Alternative.new(alternative_name, "link_color").conversion_rate
expect(previous_convertion_rate).to eq(0.0)
ab_finished("link_color")
new_convertion_rate = Split::Alternative.new(alternative_name, "link_color").conversion_rate
expect(new_convertion_rate).to eq(1.0)
end
end
describe "active experiments" do
it "should show an active test" do
alternative = ab_test("def", "4", "5", "6")
expect(active_experiments.count).to eq 1
expect(active_experiments.first[0]).to eq "def"
expect(active_experiments.first[1]).to eq alternative
end
it "should show a finished test" do
alternative = ab_test("def", "4", "5", "6")
ab_finished("def", { reset: false })
expect(active_experiments.count).to eq 1
expect(active_experiments.first[0]).to eq "def"
expect(active_experiments.first[1]).to eq alternative
end
it "should show an active test when an experiment is on a later version" do
experiment.reset
expect(experiment.version).to eq(1)
ab_test("link_color", "blue", "red")
expect(active_experiments.count).to eq 1
expect(active_experiments.first[0]).to eq "link_color"
end
it "should show versioned tests properly" do
10.times { experiment.reset }
alternative = ab_test(experiment.name, "blue", "red")
ab_finished(experiment.name, reset: false)
expect(experiment.version).to eq(10)
expect(active_experiments.count).to eq 1
expect(active_experiments).to eq({ "link_color" => alternative })
end
it "should show multiple tests" do
Split.configure do |config|
config.allow_multiple_experiments = true
end
alternative = ab_test("def", "4", "5", "6")
another_alternative = ab_test("ghi", "7", "8", "9")
expect(active_experiments.count).to eq 2
expect(active_experiments["def"]).to eq alternative
expect(active_experiments["ghi"]).to eq another_alternative
end
it "should not show tests with winners" do
Split.configure do |config|
config.allow_multiple_experiments = true
end
e = Split::ExperimentCatalog.find_or_create("def", "4", "5", "6")
e.winner = "4"
ab_test("def", "4", "5", "6")
another_alternative = ab_test("ghi", "7", "8", "9")
expect(active_experiments.count).to eq 1
expect(active_experiments.first[0]).to eq "ghi"
expect(active_experiments.first[1]).to eq another_alternative
end
end
describe "when user is a robot" do
before(:each) do
@request = OpenStruct.new(user_agent: "Googlebot/2.1 (+http://www.google.com/bot.html)")
end
describe "ab_test" do
it "should return the control" do
alternative = ab_test("link_color", "blue", "red")
expect(alternative).to eq experiment.control.name
end
it "should not create a experiment" do
ab_test("link_color", "blue", "red")
expect(Split::Experiment.new("link_color")).to be_a_new_record
end
it "should not increment the participation count" do
previous_red_count = Split::Alternative.new("red", "link_color").participant_count
previous_blue_count = Split::Alternative.new("blue", "link_color").participant_count
ab_test("link_color", "blue", "red")
new_red_count = Split::Alternative.new("red", "link_color").participant_count
new_blue_count = Split::Alternative.new("blue", "link_color").participant_count
expect((new_red_count + new_blue_count)).to eq(previous_red_count + previous_blue_count)
end
end
describe "finished" do
it "should not increment the completed count" do
alternative_name = ab_test("link_color", "blue", "red")
previous_completion_count = Split::Alternative.new(alternative_name, "link_color").completed_count
ab_finished("link_color")
new_completion_count = Split::Alternative.new(alternative_name, "link_color").completed_count
expect(new_completion_count).to eq(previous_completion_count)
end
end
end
describe "when providing custom ignore logic" do
context "using a proc to configure custom logic" do
before(:each) do
Split.configure do |c|
c.ignore_filter = proc { |request| true } # ignore everything
end
end
it "ignores the ab_test" do
ab_test("link_color", "blue", "red")
red_count = Split::Alternative.new("red", "link_color").participant_count
blue_count = Split::Alternative.new("blue", "link_color").participant_count
expect((red_count + blue_count)).to be(0)
end
end
end
shared_examples_for "a disabled test" do
describe "ab_test" do
it "should return the control" do
alternative = ab_test("link_color", "blue", "red")
expect(alternative).to eq experiment.control.name
end
it "should not increment the participation count" do
previous_red_count = Split::Alternative.new("red", "link_color").participant_count
previous_blue_count = Split::Alternative.new("blue", "link_color").participant_count
ab_test("link_color", "blue", "red")
new_red_count = Split::Alternative.new("red", "link_color").participant_count
new_blue_count = Split::Alternative.new("blue", "link_color").participant_count
expect((new_red_count + new_blue_count)).to eq(previous_red_count + previous_blue_count)
end
end
describe "finished" do
it "should not increment the completed count" do
alternative_name = ab_test("link_color", "blue", "red")
previous_completion_count = Split::Alternative.new(alternative_name, "link_color").completed_count
ab_finished("link_color")
new_completion_count = Split::Alternative.new(alternative_name, "link_color").completed_count
expect(new_completion_count).to eq(previous_completion_count)
end
end
end
describe "when ip address is ignored" do
context "individually" do
before(:each) do
@request = OpenStruct.new(ip: "81.19.48.130")
Split.configure do |c|
c.ignore_ip_addresses << "81.19.48.130"
end
end
it_behaves_like "a disabled test"
end
context "for a range" do
before(:each) do
@request = OpenStruct.new(ip: "81.19.48.129")
Split.configure do |c|
c.ignore_ip_addresses << /81\.19\.48\.[0-9]+/
end
end
it_behaves_like "a disabled test"
end
context "using both a range and a specific value" do
before(:each) do
@request = OpenStruct.new(ip: "81.19.48.128")
Split.configure do |c|
c.ignore_ip_addresses << "81.19.48.130"
c.ignore_ip_addresses << /81\.19\.48\.[0-9]+/
end
end
it_behaves_like "a disabled test"
end
context "when ignored other address" do
before do
@request = OpenStruct.new(ip: "1.1.1.1")
Split.configure do |c|
c.ignore_ip_addresses << "81.19.48.130"
end
end
it "works as usual" do
alternative_name = ab_test("link_color", "red", "blue")
expect {
ab_finished("link_color")
}.to change(Split::Alternative.new(alternative_name, "link_color"), :completed_count).by(1)
end
end
end
describe "when user is previewing" do
before(:each) do
@request = OpenStruct.new(headers: { "x-purpose" => "preview" })
end
it_behaves_like "a disabled test"
end
describe "versioned experiments" do
it "should use version zero if no version is present" do
alternative_name = ab_test("link_color", "blue", "red")
expect(experiment.version).to eq(0)
expect(ab_user["link_color"]).to eq(alternative_name)
end
it "should save the version of the experiment to the session" do
experiment.reset
expect(experiment.version).to eq(1)
alternative_name = ab_test("link_color", "blue", "red")
expect(ab_user["link_color:1"]).to eq(alternative_name)
end
it "should load the experiment even if the version is not 0" do
experiment.reset
expect(experiment.version).to eq(1)
alternative_name = ab_test("link_color", "blue", "red")
expect(ab_user["link_color:1"]).to eq(alternative_name)
return_alternative_name = ab_test("link_color", "blue", "red")
expect(return_alternative_name).to eq(alternative_name)
end
it "should reset the session of a user on an older version of the experiment" do
alternative_name = ab_test("link_color", "blue", "red")
expect(ab_user["link_color"]).to eq(alternative_name)
alternative = Split::Alternative.new(alternative_name, "link_color")
expect(alternative.participant_count).to eq(1)
experiment.reset
expect(experiment.version).to eq(1)
alternative = Split::Alternative.new(alternative_name, "link_color")
expect(alternative.participant_count).to eq(0)
new_alternative_name = ab_test("link_color", "blue", "red")
expect(ab_user["link_color:1"]).to eq(new_alternative_name)
new_alternative = Split::Alternative.new(new_alternative_name, "link_color")
expect(new_alternative.participant_count).to eq(1)
end
it "should cleanup old versions of experiments from the session" do
alternative_name = ab_test("link_color", "blue", "red")
expect(ab_user["link_color"]).to eq(alternative_name)
alternative = Split::Alternative.new(alternative_name, "link_color")
expect(alternative.participant_count).to eq(1)
experiment.reset
expect(experiment.version).to eq(1)
alternative = Split::Alternative.new(alternative_name, "link_color")
expect(alternative.participant_count).to eq(0)
new_alternative_name = ab_test("link_color", "blue", "red")
expect(ab_user["link_color:1"]).to eq(new_alternative_name)
end
it "should only count completion of users on the current version" do
alternative_name = ab_test("link_color", "blue", "red")
expect(ab_user["link_color"]).to eq(alternative_name)
Split::Alternative.new(alternative_name, "link_color")
experiment.reset
expect(experiment.version).to eq(1)
ab_finished("link_color")
alternative = Split::Alternative.new(alternative_name, "link_color")
expect(alternative.completed_count).to eq(0)
end
end
context "when redis is not available" do
before(:each) do
expect(Split).to receive(:redis).at_most(5).times.and_raise(Errno::ECONNREFUSED.new)
end
context "and db_failover config option is turned off" do
before(:each) do
Split.configure do |config|
config.db_failover = false
end
end
describe "ab_test" do
it "should raise an exception" do
expect { ab_test("link_color", "blue", "red") }.to raise_error(Errno::ECONNREFUSED)
end
end
describe "finished" do
it "should raise an exception" do
expect { ab_finished("link_color") }.to raise_error(Errno::ECONNREFUSED)
end
end
describe "disable split testing" do
before(:each) do
Split.configure do |config|
config.enabled = false
end
end
it "should not attempt to connect to redis" do
expect { ab_test("link_color", "blue", "red") }.not_to raise_error
end
it "should return control variable" do
expect(ab_test("link_color", "blue", "red")).to eq("blue")
expect { ab_finished("link_color") }.not_to raise_error
end
end
end
context "and db_failover config option is turned on" do
before(:each) do
Split.configure do |config|
config.db_failover = true
end
end
describe "ab_test" do
it "should not raise an exception" do
expect { ab_test("link_color", "blue", "red") }.not_to raise_error
end
it "should call db_failover_on_db_error proc with error as parameter" do
Split.configure do |config|
config.db_failover_on_db_error = proc do |error|
expect(error).to be_a(Errno::ECONNREFUSED)
end
end
expect(Split.configuration.db_failover_on_db_error).to receive(:call).and_call_original
ab_test("link_color", "blue", "red")
end
it "should always use first alternative" do
expect(ab_test("link_color", "blue", "red")).to eq("blue")
expect(ab_test("link_color", { "blue" => 0.01 }, "red" => 0.2)).to eq("blue")
expect(ab_test("link_color", { "blue" => 0.8 }, { "red" => 20 })).to eq("blue")
expect(ab_test("link_color", "blue", "red") do |alternative|
"shared/#{alternative}"
end).to eq("shared/blue")
end
context "and db_failover_allow_parameter_override config option is turned on" do
before(:each) do
Split.configure do |config|
config.db_failover_allow_parameter_override = true
end
end
context "and given an override parameter" do
it "should use given override instead of the first alternative" do
@params = { "ab_test" => { "link_color" => "red" } }
expect(ab_test("link_color", "blue", "red")).to eq("red")
expect(ab_test("link_color", "blue", "red", "green")).to eq("red")
expect(ab_test("link_color", { "blue" => 0.01 }, "red" => 0.2)).to eq("red")
expect(ab_test("link_color", { "blue" => 0.8 }, { "red" => 20 })).to eq("red")
expect(ab_test("link_color", "blue", "red") do |alternative|
"shared/#{alternative}"
end).to eq("shared/red")
end
end
end
context "and preloaded config given" do
before do
Split.configuration.experiments[:link_color] = {
alternatives: [ "blue", "red" ],
}
end
it "uses first alternative" do
expect(ab_test(:link_color)).to eq("blue")
end
end
end
describe "finished" do
it "should not raise an exception" do
expect { ab_finished("link_color") }.not_to raise_error
end
it "should call db_failover_on_db_error proc with error as parameter" do
Split.configure do |config|
config.db_failover_on_db_error = proc do |error|
expect(error).to be_a(Errno::ECONNREFUSED)
end
end
expect(Split.configuration.db_failover_on_db_error).to receive(:call).and_call_original
ab_finished("link_color")
end
end
end
end
context "with preloaded config" do
before { Split.configuration.experiments = {} }
it "pulls options from config file" do
Split.configuration.experiments[:my_experiment] = {
alternatives: [ "control_opt", "other_opt" ],
goals: ["goal1", "goal2"]
}
ab_test :my_experiment
expect(Split::Experiment.new(:my_experiment).alternatives.map(&:name)).to eq([ "control_opt", "other_opt" ])
expect(Split::Experiment.new(:my_experiment).goals).to eq([ "goal1", "goal2" ])
end
it "can be called multiple times" do
Split.configuration.experiments[:my_experiment] = {
alternatives: [ "control_opt", "other_opt" ],
goals: ["goal1", "goal2"]
}
5.times { ab_test :my_experiment }
experiment = Split::Experiment.new(:my_experiment)
expect(experiment.alternatives.map(&:name)).to eq([ "control_opt", "other_opt" ])
expect(experiment.goals).to eq([ "goal1", "goal2" ])
expect(experiment.participant_count).to eq(1)
end
it "accepts multiple goals" do
Split.configuration.experiments[:my_experiment] = {
alternatives: [ "control_opt", "other_opt" ],
goals: [ "goal1", "goal2", "goal3" ]
}
ab_test :my_experiment
experiment = Split::Experiment.new(:my_experiment)
expect(experiment.goals).to eq([ "goal1", "goal2", "goal3" ])
end
it "allow specifying goals to be optional" do
Split.configuration.experiments[:my_experiment] = {
alternatives: [ "control_opt", "other_opt" ]
}
experiment = Split::Experiment.new(:my_experiment)
expect(experiment.goals).to eq([])
end
it "accepts multiple alternatives" do
Split.configuration.experiments[:my_experiment] = {
alternatives: [ "control_opt", "second_opt", "third_opt" ],
}
ab_test :my_experiment
experiment = Split::Experiment.new(:my_experiment)
expect(experiment.alternatives.map(&:name)).to eq([ "control_opt", "second_opt", "third_opt" ])
end
it "accepts probability on alternatives" do
Split.configuration.experiments[:my_experiment] = {
alternatives: [
{ name: "control_opt", percent: 67 },
{ name: "second_opt", percent: 10 },
{ name: "third_opt", percent: 23 },
],
}
ab_test :my_experiment
experiment = Split::Experiment.new(:my_experiment)
expect(experiment.alternatives.collect { |a| [a.name, a.weight] }).to eq([["control_opt", 0.67], ["second_opt", 0.1], ["third_opt", 0.23]])
end
it "accepts probability on some alternatives" do
Split.configuration.experiments[:my_experiment] = {
alternatives: [
{ name: "control_opt", percent: 34 },
"second_opt",
{ name: "third_opt", percent: 23 },
"fourth_opt",
],
}
ab_test :my_experiment
experiment = Split::Experiment.new(:my_experiment)
names_and_weights = experiment.alternatives.collect { |a| [a.name, a.weight] }
expect(names_and_weights).to eq([["control_opt", 0.34], ["second_opt", 0.215], ["third_opt", 0.23], ["fourth_opt", 0.215]])
expect(names_and_weights.inject(0) { |sum, nw| sum + nw[1] }).to eq(1.0)
end
it "allows name param without probability" do
Split.configuration.experiments[:my_experiment] = {
alternatives: [
{ name: "control_opt" },
"second_opt",
{ name: "third_opt", percent: 64 },
],
}
ab_test :my_experiment
experiment = Split::Experiment.new(:my_experiment)
names_and_weights = experiment.alternatives.collect { |a| [a.name, a.weight] }
expect(names_and_weights).to eq([["control_opt", 0.18], ["second_opt", 0.18], ["third_opt", 0.64]])
expect(names_and_weights.inject(0) { |sum, nw| sum + nw[1] }).to eq(1.0)
end
it "fails gracefully if config is missing experiment" do
Split.configuration.experiments = { other_experiment: { foo: "Bar" } }
expect { ab_test :my_experiment }.to raise_error(Split::ExperimentNotFound)
end
it "fails gracefully if config is missing" do
expect { Split.configuration.experiments = nil }.to raise_error(Split::InvalidExperimentsFormatError)
end
it "fails gracefully if config is missing alternatives" do
Split.configuration.experiments[:my_experiment] = { foo: "Bar" }
expect { ab_test :my_experiment }.to raise_error(NoMethodError)
end
end
it "should handle multiple experiments correctly" do
experiment2 = Split::ExperimentCatalog.find_or_create("link_color2", "blue", "red")
ab_test("link_color", "blue", "red")
ab_test("link_color2", "blue", "red")
ab_finished("link_color2")
experiment2.alternatives.each do |alt|
expect(alt.unfinished_count).to eq(0)
end
end
context "with goals" do
before do
@experiment = { "link_color" => ["purchase", "refund"] }
@alternatives = ["blue", "red"]
@experiment_name, @goals = normalize_metric(@experiment)
@goal1 = @goals[0]
@goal2 = @goals[1]
end
it "should normalize experiment" do
expect(@experiment_name).to eq("link_color")
expect(@goals).to eq(["purchase", "refund"])
end
describe "ab_test" do
it "should allow experiment goals interface as a single hash" do
ab_test(@experiment, *@alternatives)
experiment = Split::ExperimentCatalog.find("link_color")
expect(experiment.goals).to eq(["purchase", "refund"])
end
end
describe "ab_finished" do
before do
@alternative_name = ab_test(@experiment, *@alternatives)
end
it "should increment the counter for the specified-goal completed alternative" do
expect { ab_finished({ "link_color" => ["purchase"] }) }
.to change { Split::Alternative.new(@alternative_name, @experiment_name).completed_count(@goal2) }.by(0)
.and change { Split::Alternative.new(@alternative_name, @experiment_name).completed_count(@goal1) }.by(1)
end
end
end
end
<MSG> More issues for finished(:reset => false)
When a user completes a test but reset is set to false, when they hit ab_test again they will get the control alternative. This is because doing_other_tests? was doing the same as issue #83 and counting the finished result as another experiment. This fixes that.
<DFF> @@ -177,6 +177,12 @@ describe Split::Helper do
session[:split] = nil
lambda { finished('some_experiment_not_started_by_the_user') }.should_not raise_exception
end
+
+ it 'should not be doing other tests when it has completed one that has :reset => false' do
+ ab_user[@experiment.key] = @alternative_name
+ ab_user[@experiment.finished_key] = true
+ doing_other_tests?(@experiment.key).should be false
+ end
end
describe 'conversions' do
| 6 | More issues for finished(:reset => false) | 0 | .rb | rb | mit | splitrb/split |
10071855 | <NME> helper_spec.rb
<BEF> # frozen_string_literal: true
require "spec_helper"
# TODO change some of these tests to use Rack::Test
describe Split::Helper do
include Split::Helper
let(:experiment) {
Split::ExperimentCatalog.find_or_create("link_color", "blue", "red")
}
describe "ab_test" do
it "should not raise an error when passed strings for alternatives" do
expect { ab_test("xyz", "1", "2", "3") }.not_to raise_error
end
it "should not raise an error when passed an array for alternatives" do
expect { ab_test("xyz", ["1", "2", "3"]) }.not_to raise_error
end
it "should raise the appropriate error when passed integers for alternatives" do
expect { ab_test("xyz", 1, 2, 3) }.to raise_error(ArgumentError)
end
it "should raise the appropriate error when passed symbols for alternatives" do
expect { ab_test("xyz", :a, :b, :c) }.to raise_error(ArgumentError)
end
it "should not raise error when passed an array for goals" do
expect { ab_test({ "link_color" => ["purchase", "refund"] }, "blue", "red") }.not_to raise_error
end
it "should not raise error when passed just one goal" do
expect { ab_test({ "link_color" => "purchase" }, "blue", "red") }.not_to raise_error
end
it "raises an appropriate error when processing combined expirements" do
Split.configuration.experiments = {
combined_exp_1: {
alternatives: [ { name: "control", percent: 50 }, { name: "test-alt", percent: 50 } ],
metric: :my_metric,
combined_experiments: [:combined_exp_1_sub_1]
}
}
Split::ExperimentCatalog.find_or_create("combined_exp_1")
expect { ab_test("combined_exp_1") }.to raise_error(Split::InvalidExperimentsFormatError)
end
it "should assign a random alternative to a new user when there are an equal number of alternatives assigned" do
ab_test("link_color", "blue", "red")
expect(["red", "blue"]).to include(ab_user["link_color"])
end
it "should increment the participation counter after assignment to a new user" do
previous_red_count = Split::Alternative.new("red", "link_color").participant_count
previous_blue_count = Split::Alternative.new("blue", "link_color").participant_count
ab_test("link_color", "blue", "red")
new_red_count = Split::Alternative.new("red", "link_color").participant_count
new_blue_count = Split::Alternative.new("blue", "link_color").participant_count
expect((new_red_count + new_blue_count)).to eq(previous_red_count + previous_blue_count + 1)
end
it "should not increment the counter for an experiment that the user is not participating in" do
ab_test("link_color", "blue", "red")
e = Split::ExperimentCatalog.find_or_create("button_size", "small", "big")
expect {
# User shouldn't participate in this second experiment
ab_test("button_size", "small", "big")
}.not_to change { e.participant_count }
end
it "should not increment the counter for an ended experiment" do
e = Split::ExperimentCatalog.find_or_create("button_size", "small", "big")
e.winner = "small"
expect {
a = ab_test("button_size", "small", "big")
expect(a).to eq("small")
}.not_to change { e.participant_count }
end
it "should not increment the counter for an not started experiment" do
expect(Split.configuration).to receive(:start_manually).and_return(true)
e = Split::ExperimentCatalog.find_or_create("button_size", "small", "big")
expect {
a = ab_test("button_size", "small", "big")
expect(a).to eq("small")
}.not_to change { e.participant_count }
end
it "should return the given alternative for an existing user" do
expect(ab_test("link_color", "blue", "red")).to eq ab_test("link_color", "blue", "red")
end
it "should always return the winner if one is present" do
experiment.winner = "orange"
expect(ab_test("link_color", "blue", "red")).to eq("orange")
end
it "should allow the alternative to be forced by passing it in the params" do
# ?ab_test[link_color]=blue
@params = { "ab_test" => { "link_color" => "blue" } }
alternative = ab_test("link_color", "blue", "red")
expect(alternative).to eq("blue")
alternative = ab_test("link_color", { "blue" => 1 }, "red" => 5)
expect(alternative).to eq("blue")
@params = { "ab_test" => { "link_color" => "red" } }
alternative = ab_test("link_color", "blue", "red")
expect(alternative).to eq("red")
alternative = ab_test("link_color", { "blue" => 5 }, "red" => 1)
expect(alternative).to eq("red")
end
it "should not allow an arbitrary alternative" do
@params = { "ab_test" => { "link_color" => "pink" } }
alternative = ab_test("link_color", "blue")
expect(alternative).to eq("blue")
end
it "should not store the split when a param forced alternative" do
@params = { "ab_test" => { "link_color" => "blue" } }
expect(ab_user).not_to receive(:[]=)
ab_test("link_color", "blue", "red")
end
it "SPLIT_DISABLE query parameter should also force the alternative (uses control)" do
@params = { "SPLIT_DISABLE" => "true" }
alternative = ab_test("link_color", "blue", "red")
expect(alternative).to eq("blue")
alternative = ab_test("link_color", { "blue" => 1 }, "red" => 5)
expect(alternative).to eq("blue")
alternative = ab_test("link_color", "red", "blue")
expect(alternative).to eq("red")
alternative = ab_test("link_color", { "red" => 5 }, "blue" => 1)
expect(alternative).to eq("red")
end
it "should not store the split when Split generically disabled" do
@params = { "SPLIT_DISABLE" => "true" }
expect(ab_user).not_to receive(:[]=)
ab_test("link_color", "blue", "red")
end
context "when store_override is set" do
before { Split.configuration.store_override = true }
it "should store the forced alternative" do
@params = { "ab_test" => { "link_color" => "blue" } }
expect(ab_user).to receive(:[]=).with("link_color", "blue")
ab_test("link_color", "blue", "red")
end
end
context "when on_trial_choose is set" do
before { Split.configuration.on_trial_choose = :some_method }
it "should call the method" do
expect(self).to receive(:some_method)
ab_test("link_color", "blue", "red")
end
end
it "should allow passing a block" do
alt = ab_test("link_color", "blue", "red")
ret = ab_test("link_color", "blue", "red") { |alternative| "shared/#{alternative}" }
expect(ret).to eq("shared/#{alt}")
end
session[:split] = nil
lambda { finished('some_experiment_not_started_by_the_user') }.should_not raise_exception
end
end
describe 'conversions' do
it "should only let a user participate in one experiment at a time" do
link_color = ab_test("link_color", "blue", "red")
ab_test("button_size", "small", "big")
expect(ab_user["link_color"]).to eq(link_color)
big = Split::Alternative.new("big", "button_size")
expect(big.participant_count).to eq(0)
small = Split::Alternative.new("small", "button_size")
expect(small.participant_count).to eq(0)
end
it "should let a user participate in many experiment with allow_multiple_experiments option" do
Split.configure do |config|
config.allow_multiple_experiments = true
end
link_color = ab_test("link_color", "blue", "red")
button_size = ab_test("button_size", "small", "big")
expect(ab_user["link_color"]).to eq(link_color)
expect(ab_user["button_size"]).to eq(button_size)
button_size_alt = Split::Alternative.new(button_size, "button_size")
expect(button_size_alt.participant_count).to eq(1)
end
context "with allow_multiple_experiments = 'control'" do
it "should let a user participate in many experiment with one non-'control' alternative" do
Split.configure do |config|
config.allow_multiple_experiments = "control"
end
groups = 100.times.map do |n|
ab_test("test#{n}".to_sym, { "control" => (100 - n) }, { "test#{n}-alt" => n })
end
experiments = ab_user.active_experiments
expect(experiments.size).to be > 1
count_control = experiments.values.count { |g| g == "control" }
expect(count_control).to eq(experiments.size - 1)
count_alts = groups.count { |g| g != "control" }
expect(count_alts).to eq(1)
end
context "when user already has experiment" do
let(:mock_user) { Split::User.new(self, { "test_0" => "test-alt" }) }
before do
Split.configure do |config|
config.allow_multiple_experiments = "control"
end
Split::ExperimentCatalog.find_or_initialize("test_0", "control", "test-alt").save
Split::ExperimentCatalog.find_or_initialize("test_1", "control", "test-alt").save
end
it "should restore previously selected alternative" do
expect(ab_user.active_experiments.size).to eq 1
expect(ab_test(:test_0, { "control" => 100 }, { "test-alt" => 1 })).to eq "test-alt"
expect(ab_test(:test_0, { "control" => 1 }, { "test-alt" => 100 })).to eq "test-alt"
end
it "should select the correct alternatives after experiment resets" do
experiment = Split::ExperimentCatalog.find(:test_0)
experiment.reset
mock_user[experiment.key] = "test-alt"
expect(ab_user.active_experiments.size).to eq 1
expect(ab_test(:test_0, { "control" => 100 }, { "test-alt" => 1 })).to eq "test-alt"
expect(ab_test(:test_0, { "control" => 0 }, { "test-alt" => 100 })).to eq "test-alt"
end
it "lets override existing choice" do
pending "this requires user store reset on first call not depending on whelther it is current trial"
@params = { "ab_test" => { "test_1" => "test-alt" } }
expect(ab_test(:test_0, { "control" => 0 }, { "test-alt" => 100 })).to eq "control"
expect(ab_test(:test_1, { "control" => 100 }, { "test-alt" => 1 })).to eq "test-alt"
end
end
end
it "should not over-write a finished key when an experiment is on a later version" do
experiment.increment_version
ab_user = { experiment.key => "blue", experiment.finished_key => true }
finished_session = ab_user.dup
ab_test("link_color", "blue", "red")
expect(ab_user).to eq(finished_session)
end
end
describe "metadata" do
context "is defined" do
before do
Split.configuration.experiments = {
my_experiment: {
alternatives: ["one", "two"],
resettable: false,
metadata: { "one" => "Meta1", "two" => "Meta2" }
}
}
end
it "should be passed to helper block" do
@params = { "ab_test" => { "my_experiment" => "two" } }
expect(ab_test("my_experiment")).to eq "two"
expect(ab_test("my_experiment") do |alternative, meta|
meta
end).to eq("Meta2")
end
it "should pass control metadata helper block if library disabled" do
Split.configure do |config|
config.enabled = false
end
expect(ab_test("my_experiment")).to eq "one"
expect(ab_test("my_experiment") do |_, meta|
meta
end).to eq("Meta1")
end
end
context "is not defined" do
before do
Split.configuration.experiments = {
my_experiment: {
alternatives: ["one", "two"],
resettable: false,
metadata: nil
}
}
end
it "should be passed to helper block" do
expect(ab_test("my_experiment") do |alternative, meta|
meta
end).to eq({})
end
it "should pass control metadata helper block if library disabled" do
Split.configure do |config|
config.enabled = false
end
expect(ab_test("my_experiment") do |_, meta|
meta
end).to eq({})
end
end
end
describe "ab_finished" do
context "for an experiment that the user participates in" do
before(:each) do
@experiment_name = "link_color"
@alternatives = ["blue", "red"]
@experiment = Split::ExperimentCatalog.find_or_create(@experiment_name, *@alternatives)
@alternative_name = ab_test(@experiment_name, *@alternatives)
@previous_completion_count = Split::Alternative.new(@alternative_name, @experiment_name).completed_count
end
it "should increment the counter for the completed alternative" do
ab_finished(@experiment_name)
new_completion_count = Split::Alternative.new(@alternative_name, @experiment_name).completed_count
expect(new_completion_count).to eq(@previous_completion_count + 1)
end
it "should set experiment's finished key if reset is false" do
ab_finished(@experiment_name, { reset: false })
expect(ab_user[@experiment.key]).to eq(@alternative_name)
expect(ab_user[@experiment.finished_key]).to eq(true)
end
it "should not increment the counter if reset is false and the experiment has been already finished" do
2.times { ab_finished(@experiment_name, { reset: false }) }
new_completion_count = Split::Alternative.new(@alternative_name, @experiment_name).completed_count
expect(new_completion_count).to eq(@previous_completion_count + 1)
end
it "should not increment the counter for an ended experiment" do
e = Split::ExperimentCatalog.find_or_create("button_size", "small", "big")
e.winner = "small"
a = ab_test("button_size", "small", "big")
expect(a).to eq("small")
expect {
ab_finished("button_size")
}.not_to change { Split::Alternative.new(a, "button_size").completed_count }
end
it "should clear out the user's participation from their session" do
expect(ab_user[@experiment.key]).to eq(@alternative_name)
ab_finished(@experiment_name)
expect(ab_user.keys).to be_empty
end
it "should not clear out the users session if reset is false" do
expect(ab_user[@experiment.key]).to eq(@alternative_name)
ab_finished(@experiment_name, { reset: false })
expect(ab_user[@experiment.key]).to eq(@alternative_name)
expect(ab_user[@experiment.finished_key]).to eq(true)
end
it "should reset the users session when experiment is not versioned" do
expect(ab_user[@experiment.key]).to eq(@alternative_name)
ab_finished(@experiment_name)
expect(ab_user.keys).to be_empty
end
it "should reset the users session when experiment is versioned" do
@experiment.increment_version
@alternative_name = ab_test(@experiment_name, *@alternatives)
expect(ab_user[@experiment.key]).to eq(@alternative_name)
ab_finished(@experiment_name)
expect(ab_user.keys).to be_empty
end
context "when on_trial_complete is set" do
before { Split.configuration.on_trial_complete = :some_method }
it "should call the method" do
expect(self).to receive(:some_method)
ab_finished(@experiment_name)
end
it "should not call the method without alternative" do
ab_user[@experiment.key] = nil
expect(self).not_to receive(:some_method)
ab_finished(@experiment_name)
end
end
end
context "for an experiment that the user is excluded from" do
before do
alternative = ab_test("link_color", "blue", "red")
expect(Split::Alternative.new(alternative, "link_color").participant_count).to eq(1)
alternative = ab_test("button_size", "small", "big")
expect(Split::Alternative.new(alternative, "button_size").participant_count).to eq(0)
end
it "should not increment the completed counter" do
# So, user should be participating in the link_color experiment and
# receive the control for button_size. As the user is not participating in
# the button size experiment, finishing it should not increase the
# completion count for that alternative.
expect {
ab_finished("button_size")
}.not_to change { Split::Alternative.new("small", "button_size").completed_count }
end
end
context "for an experiment that the user does not participate in" do
before do
Split::ExperimentCatalog.find_or_create(:not_started_experiment, "control", "alt")
end
it "should not raise an exception" do
expect { ab_finished(:not_started_experiment) }.not_to raise_exception
end
it "should not change the user state when reset is false" do
expect { ab_finished(:not_started_experiment, reset: false) }.not_to change { ab_user.keys }.from([])
end
it "should not change the user state when reset is true" do
expect(self).not_to receive(:reset!)
ab_finished(:not_started_experiment)
end
it "should not increment the completed counter" do
ab_finished(:not_started_experiment)
expect(Split::Alternative.new("control", :not_started_experiment).completed_count).to eq(0)
expect(Split::Alternative.new("alt", :not_started_experiment).completed_count).to eq(0)
end
end
end
context "finished with config" do
it "passes reset option" do
Split.configuration.experiments = {
my_experiment: {
alternatives: ["one", "two"],
resettable: false,
}
}
alternative = ab_test(:my_experiment)
experiment = Split::ExperimentCatalog.find :my_experiment
ab_finished :my_experiment
expect(ab_user[experiment.key]).to eq(alternative)
expect(ab_user[experiment.finished_key]).to eq(true)
end
end
context "finished with metric name" do
before { Split.configuration.experiments = {} }
before { expect(Split::Alternative).to receive(:new).at_least(1).times.and_call_original }
def should_finish_experiment(experiment_name, should_finish = true)
alts = Split.configuration.experiments[experiment_name][:alternatives]
experiment = Split::ExperimentCatalog.find_or_create(experiment_name, *alts)
alt_name = ab_user[experiment.key] = alts.first
alt = double("alternative")
expect(alt).to receive(:name).at_most(1).times.and_return(alt_name)
expect(Split::Alternative).to receive(:new).at_most(1).times.with(alt_name, experiment_name.to_s).and_return(alt)
if should_finish
expect(alt).to receive(:increment_completion).at_most(1).times
else
expect(alt).not_to receive(:increment_completion)
end
end
it "completes the test" do
Split.configuration.experiments[:my_experiment] = {
alternatives: [ "control_opt", "other_opt" ],
metric: :my_metric
}
should_finish_experiment :my_experiment
ab_finished :my_metric
end
it "completes all relevant tests" do
Split.configuration.experiments = {
exp_1: {
alternatives: [ "1-1", "1-2" ],
metric: :my_metric
},
exp_2: {
alternatives: [ "2-1", "2-2" ],
metric: :another_metric
},
exp_3: {
alternatives: [ "3-1", "3-2" ],
metric: :my_metric
},
}
should_finish_experiment :exp_1
should_finish_experiment :exp_2, false
should_finish_experiment :exp_3
ab_finished :my_metric
end
it "passes reset option" do
Split.configuration.experiments = {
my_exp: {
alternatives: ["one", "two"],
metric: :my_metric,
resettable: false,
}
}
alternative_name = ab_test(:my_exp)
exp = Split::ExperimentCatalog.find :my_exp
ab_finished :my_metric
expect(ab_user[exp.key]).to eq(alternative_name)
expect(ab_user[exp.finished_key]).to be_truthy
end
it "passes through options" do
Split.configuration.experiments = {
my_exp: {
alternatives: ["one", "two"],
metric: :my_metric,
}
}
alternative_name = ab_test(:my_exp)
exp = Split::ExperimentCatalog.find :my_exp
ab_finished :my_metric, reset: false
expect(ab_user[exp.key]).to eq(alternative_name)
expect(ab_user[exp.finished_key]).to be_truthy
end
end
describe "conversions" do
it "should return a conversion rate for an alternative" do
alternative_name = ab_test("link_color", "blue", "red")
previous_convertion_rate = Split::Alternative.new(alternative_name, "link_color").conversion_rate
expect(previous_convertion_rate).to eq(0.0)
ab_finished("link_color")
new_convertion_rate = Split::Alternative.new(alternative_name, "link_color").conversion_rate
expect(new_convertion_rate).to eq(1.0)
end
end
describe "active experiments" do
it "should show an active test" do
alternative = ab_test("def", "4", "5", "6")
expect(active_experiments.count).to eq 1
expect(active_experiments.first[0]).to eq "def"
expect(active_experiments.first[1]).to eq alternative
end
it "should show a finished test" do
alternative = ab_test("def", "4", "5", "6")
ab_finished("def", { reset: false })
expect(active_experiments.count).to eq 1
expect(active_experiments.first[0]).to eq "def"
expect(active_experiments.first[1]).to eq alternative
end
it "should show an active test when an experiment is on a later version" do
experiment.reset
expect(experiment.version).to eq(1)
ab_test("link_color", "blue", "red")
expect(active_experiments.count).to eq 1
expect(active_experiments.first[0]).to eq "link_color"
end
it "should show versioned tests properly" do
10.times { experiment.reset }
alternative = ab_test(experiment.name, "blue", "red")
ab_finished(experiment.name, reset: false)
expect(experiment.version).to eq(10)
expect(active_experiments.count).to eq 1
expect(active_experiments).to eq({ "link_color" => alternative })
end
it "should show multiple tests" do
Split.configure do |config|
config.allow_multiple_experiments = true
end
alternative = ab_test("def", "4", "5", "6")
another_alternative = ab_test("ghi", "7", "8", "9")
expect(active_experiments.count).to eq 2
expect(active_experiments["def"]).to eq alternative
expect(active_experiments["ghi"]).to eq another_alternative
end
it "should not show tests with winners" do
Split.configure do |config|
config.allow_multiple_experiments = true
end
e = Split::ExperimentCatalog.find_or_create("def", "4", "5", "6")
e.winner = "4"
ab_test("def", "4", "5", "6")
another_alternative = ab_test("ghi", "7", "8", "9")
expect(active_experiments.count).to eq 1
expect(active_experiments.first[0]).to eq "ghi"
expect(active_experiments.first[1]).to eq another_alternative
end
end
describe "when user is a robot" do
before(:each) do
@request = OpenStruct.new(user_agent: "Googlebot/2.1 (+http://www.google.com/bot.html)")
end
describe "ab_test" do
it "should return the control" do
alternative = ab_test("link_color", "blue", "red")
expect(alternative).to eq experiment.control.name
end
it "should not create a experiment" do
ab_test("link_color", "blue", "red")
expect(Split::Experiment.new("link_color")).to be_a_new_record
end
it "should not increment the participation count" do
previous_red_count = Split::Alternative.new("red", "link_color").participant_count
previous_blue_count = Split::Alternative.new("blue", "link_color").participant_count
ab_test("link_color", "blue", "red")
new_red_count = Split::Alternative.new("red", "link_color").participant_count
new_blue_count = Split::Alternative.new("blue", "link_color").participant_count
expect((new_red_count + new_blue_count)).to eq(previous_red_count + previous_blue_count)
end
end
describe "finished" do
it "should not increment the completed count" do
alternative_name = ab_test("link_color", "blue", "red")
previous_completion_count = Split::Alternative.new(alternative_name, "link_color").completed_count
ab_finished("link_color")
new_completion_count = Split::Alternative.new(alternative_name, "link_color").completed_count
expect(new_completion_count).to eq(previous_completion_count)
end
end
end
describe "when providing custom ignore logic" do
context "using a proc to configure custom logic" do
before(:each) do
Split.configure do |c|
c.ignore_filter = proc { |request| true } # ignore everything
end
end
it "ignores the ab_test" do
ab_test("link_color", "blue", "red")
red_count = Split::Alternative.new("red", "link_color").participant_count
blue_count = Split::Alternative.new("blue", "link_color").participant_count
expect((red_count + blue_count)).to be(0)
end
end
end
shared_examples_for "a disabled test" do
describe "ab_test" do
it "should return the control" do
alternative = ab_test("link_color", "blue", "red")
expect(alternative).to eq experiment.control.name
end
it "should not increment the participation count" do
previous_red_count = Split::Alternative.new("red", "link_color").participant_count
previous_blue_count = Split::Alternative.new("blue", "link_color").participant_count
ab_test("link_color", "blue", "red")
new_red_count = Split::Alternative.new("red", "link_color").participant_count
new_blue_count = Split::Alternative.new("blue", "link_color").participant_count
expect((new_red_count + new_blue_count)).to eq(previous_red_count + previous_blue_count)
end
end
describe "finished" do
it "should not increment the completed count" do
alternative_name = ab_test("link_color", "blue", "red")
previous_completion_count = Split::Alternative.new(alternative_name, "link_color").completed_count
ab_finished("link_color")
new_completion_count = Split::Alternative.new(alternative_name, "link_color").completed_count
expect(new_completion_count).to eq(previous_completion_count)
end
end
end
describe "when ip address is ignored" do
context "individually" do
before(:each) do
@request = OpenStruct.new(ip: "81.19.48.130")
Split.configure do |c|
c.ignore_ip_addresses << "81.19.48.130"
end
end
it_behaves_like "a disabled test"
end
context "for a range" do
before(:each) do
@request = OpenStruct.new(ip: "81.19.48.129")
Split.configure do |c|
c.ignore_ip_addresses << /81\.19\.48\.[0-9]+/
end
end
it_behaves_like "a disabled test"
end
context "using both a range and a specific value" do
before(:each) do
@request = OpenStruct.new(ip: "81.19.48.128")
Split.configure do |c|
c.ignore_ip_addresses << "81.19.48.130"
c.ignore_ip_addresses << /81\.19\.48\.[0-9]+/
end
end
it_behaves_like "a disabled test"
end
context "when ignored other address" do
before do
@request = OpenStruct.new(ip: "1.1.1.1")
Split.configure do |c|
c.ignore_ip_addresses << "81.19.48.130"
end
end
it "works as usual" do
alternative_name = ab_test("link_color", "red", "blue")
expect {
ab_finished("link_color")
}.to change(Split::Alternative.new(alternative_name, "link_color"), :completed_count).by(1)
end
end
end
describe "when user is previewing" do
before(:each) do
@request = OpenStruct.new(headers: { "x-purpose" => "preview" })
end
it_behaves_like "a disabled test"
end
describe "versioned experiments" do
it "should use version zero if no version is present" do
alternative_name = ab_test("link_color", "blue", "red")
expect(experiment.version).to eq(0)
expect(ab_user["link_color"]).to eq(alternative_name)
end
it "should save the version of the experiment to the session" do
experiment.reset
expect(experiment.version).to eq(1)
alternative_name = ab_test("link_color", "blue", "red")
expect(ab_user["link_color:1"]).to eq(alternative_name)
end
it "should load the experiment even if the version is not 0" do
experiment.reset
expect(experiment.version).to eq(1)
alternative_name = ab_test("link_color", "blue", "red")
expect(ab_user["link_color:1"]).to eq(alternative_name)
return_alternative_name = ab_test("link_color", "blue", "red")
expect(return_alternative_name).to eq(alternative_name)
end
it "should reset the session of a user on an older version of the experiment" do
alternative_name = ab_test("link_color", "blue", "red")
expect(ab_user["link_color"]).to eq(alternative_name)
alternative = Split::Alternative.new(alternative_name, "link_color")
expect(alternative.participant_count).to eq(1)
experiment.reset
expect(experiment.version).to eq(1)
alternative = Split::Alternative.new(alternative_name, "link_color")
expect(alternative.participant_count).to eq(0)
new_alternative_name = ab_test("link_color", "blue", "red")
expect(ab_user["link_color:1"]).to eq(new_alternative_name)
new_alternative = Split::Alternative.new(new_alternative_name, "link_color")
expect(new_alternative.participant_count).to eq(1)
end
it "should cleanup old versions of experiments from the session" do
alternative_name = ab_test("link_color", "blue", "red")
expect(ab_user["link_color"]).to eq(alternative_name)
alternative = Split::Alternative.new(alternative_name, "link_color")
expect(alternative.participant_count).to eq(1)
experiment.reset
expect(experiment.version).to eq(1)
alternative = Split::Alternative.new(alternative_name, "link_color")
expect(alternative.participant_count).to eq(0)
new_alternative_name = ab_test("link_color", "blue", "red")
expect(ab_user["link_color:1"]).to eq(new_alternative_name)
end
it "should only count completion of users on the current version" do
alternative_name = ab_test("link_color", "blue", "red")
expect(ab_user["link_color"]).to eq(alternative_name)
Split::Alternative.new(alternative_name, "link_color")
experiment.reset
expect(experiment.version).to eq(1)
ab_finished("link_color")
alternative = Split::Alternative.new(alternative_name, "link_color")
expect(alternative.completed_count).to eq(0)
end
end
context "when redis is not available" do
before(:each) do
expect(Split).to receive(:redis).at_most(5).times.and_raise(Errno::ECONNREFUSED.new)
end
context "and db_failover config option is turned off" do
before(:each) do
Split.configure do |config|
config.db_failover = false
end
end
describe "ab_test" do
it "should raise an exception" do
expect { ab_test("link_color", "blue", "red") }.to raise_error(Errno::ECONNREFUSED)
end
end
describe "finished" do
it "should raise an exception" do
expect { ab_finished("link_color") }.to raise_error(Errno::ECONNREFUSED)
end
end
describe "disable split testing" do
before(:each) do
Split.configure do |config|
config.enabled = false
end
end
it "should not attempt to connect to redis" do
expect { ab_test("link_color", "blue", "red") }.not_to raise_error
end
it "should return control variable" do
expect(ab_test("link_color", "blue", "red")).to eq("blue")
expect { ab_finished("link_color") }.not_to raise_error
end
end
end
context "and db_failover config option is turned on" do
before(:each) do
Split.configure do |config|
config.db_failover = true
end
end
describe "ab_test" do
it "should not raise an exception" do
expect { ab_test("link_color", "blue", "red") }.not_to raise_error
end
it "should call db_failover_on_db_error proc with error as parameter" do
Split.configure do |config|
config.db_failover_on_db_error = proc do |error|
expect(error).to be_a(Errno::ECONNREFUSED)
end
end
expect(Split.configuration.db_failover_on_db_error).to receive(:call).and_call_original
ab_test("link_color", "blue", "red")
end
it "should always use first alternative" do
expect(ab_test("link_color", "blue", "red")).to eq("blue")
expect(ab_test("link_color", { "blue" => 0.01 }, "red" => 0.2)).to eq("blue")
expect(ab_test("link_color", { "blue" => 0.8 }, { "red" => 20 })).to eq("blue")
expect(ab_test("link_color", "blue", "red") do |alternative|
"shared/#{alternative}"
end).to eq("shared/blue")
end
context "and db_failover_allow_parameter_override config option is turned on" do
before(:each) do
Split.configure do |config|
config.db_failover_allow_parameter_override = true
end
end
context "and given an override parameter" do
it "should use given override instead of the first alternative" do
@params = { "ab_test" => { "link_color" => "red" } }
expect(ab_test("link_color", "blue", "red")).to eq("red")
expect(ab_test("link_color", "blue", "red", "green")).to eq("red")
expect(ab_test("link_color", { "blue" => 0.01 }, "red" => 0.2)).to eq("red")
expect(ab_test("link_color", { "blue" => 0.8 }, { "red" => 20 })).to eq("red")
expect(ab_test("link_color", "blue", "red") do |alternative|
"shared/#{alternative}"
end).to eq("shared/red")
end
end
end
context "and preloaded config given" do
before do
Split.configuration.experiments[:link_color] = {
alternatives: [ "blue", "red" ],
}
end
it "uses first alternative" do
expect(ab_test(:link_color)).to eq("blue")
end
end
end
describe "finished" do
it "should not raise an exception" do
expect { ab_finished("link_color") }.not_to raise_error
end
it "should call db_failover_on_db_error proc with error as parameter" do
Split.configure do |config|
config.db_failover_on_db_error = proc do |error|
expect(error).to be_a(Errno::ECONNREFUSED)
end
end
expect(Split.configuration.db_failover_on_db_error).to receive(:call).and_call_original
ab_finished("link_color")
end
end
end
end
context "with preloaded config" do
before { Split.configuration.experiments = {} }
it "pulls options from config file" do
Split.configuration.experiments[:my_experiment] = {
alternatives: [ "control_opt", "other_opt" ],
goals: ["goal1", "goal2"]
}
ab_test :my_experiment
expect(Split::Experiment.new(:my_experiment).alternatives.map(&:name)).to eq([ "control_opt", "other_opt" ])
expect(Split::Experiment.new(:my_experiment).goals).to eq([ "goal1", "goal2" ])
end
it "can be called multiple times" do
Split.configuration.experiments[:my_experiment] = {
alternatives: [ "control_opt", "other_opt" ],
goals: ["goal1", "goal2"]
}
5.times { ab_test :my_experiment }
experiment = Split::Experiment.new(:my_experiment)
expect(experiment.alternatives.map(&:name)).to eq([ "control_opt", "other_opt" ])
expect(experiment.goals).to eq([ "goal1", "goal2" ])
expect(experiment.participant_count).to eq(1)
end
it "accepts multiple goals" do
Split.configuration.experiments[:my_experiment] = {
alternatives: [ "control_opt", "other_opt" ],
goals: [ "goal1", "goal2", "goal3" ]
}
ab_test :my_experiment
experiment = Split::Experiment.new(:my_experiment)
expect(experiment.goals).to eq([ "goal1", "goal2", "goal3" ])
end
it "allow specifying goals to be optional" do
Split.configuration.experiments[:my_experiment] = {
alternatives: [ "control_opt", "other_opt" ]
}
experiment = Split::Experiment.new(:my_experiment)
expect(experiment.goals).to eq([])
end
it "accepts multiple alternatives" do
Split.configuration.experiments[:my_experiment] = {
alternatives: [ "control_opt", "second_opt", "third_opt" ],
}
ab_test :my_experiment
experiment = Split::Experiment.new(:my_experiment)
expect(experiment.alternatives.map(&:name)).to eq([ "control_opt", "second_opt", "third_opt" ])
end
it "accepts probability on alternatives" do
Split.configuration.experiments[:my_experiment] = {
alternatives: [
{ name: "control_opt", percent: 67 },
{ name: "second_opt", percent: 10 },
{ name: "third_opt", percent: 23 },
],
}
ab_test :my_experiment
experiment = Split::Experiment.new(:my_experiment)
expect(experiment.alternatives.collect { |a| [a.name, a.weight] }).to eq([["control_opt", 0.67], ["second_opt", 0.1], ["third_opt", 0.23]])
end
it "accepts probability on some alternatives" do
Split.configuration.experiments[:my_experiment] = {
alternatives: [
{ name: "control_opt", percent: 34 },
"second_opt",
{ name: "third_opt", percent: 23 },
"fourth_opt",
],
}
ab_test :my_experiment
experiment = Split::Experiment.new(:my_experiment)
names_and_weights = experiment.alternatives.collect { |a| [a.name, a.weight] }
expect(names_and_weights).to eq([["control_opt", 0.34], ["second_opt", 0.215], ["third_opt", 0.23], ["fourth_opt", 0.215]])
expect(names_and_weights.inject(0) { |sum, nw| sum + nw[1] }).to eq(1.0)
end
it "allows name param without probability" do
Split.configuration.experiments[:my_experiment] = {
alternatives: [
{ name: "control_opt" },
"second_opt",
{ name: "third_opt", percent: 64 },
],
}
ab_test :my_experiment
experiment = Split::Experiment.new(:my_experiment)
names_and_weights = experiment.alternatives.collect { |a| [a.name, a.weight] }
expect(names_and_weights).to eq([["control_opt", 0.18], ["second_opt", 0.18], ["third_opt", 0.64]])
expect(names_and_weights.inject(0) { |sum, nw| sum + nw[1] }).to eq(1.0)
end
it "fails gracefully if config is missing experiment" do
Split.configuration.experiments = { other_experiment: { foo: "Bar" } }
expect { ab_test :my_experiment }.to raise_error(Split::ExperimentNotFound)
end
it "fails gracefully if config is missing" do
expect { Split.configuration.experiments = nil }.to raise_error(Split::InvalidExperimentsFormatError)
end
it "fails gracefully if config is missing alternatives" do
Split.configuration.experiments[:my_experiment] = { foo: "Bar" }
expect { ab_test :my_experiment }.to raise_error(NoMethodError)
end
end
it "should handle multiple experiments correctly" do
experiment2 = Split::ExperimentCatalog.find_or_create("link_color2", "blue", "red")
ab_test("link_color", "blue", "red")
ab_test("link_color2", "blue", "red")
ab_finished("link_color2")
experiment2.alternatives.each do |alt|
expect(alt.unfinished_count).to eq(0)
end
end
context "with goals" do
before do
@experiment = { "link_color" => ["purchase", "refund"] }
@alternatives = ["blue", "red"]
@experiment_name, @goals = normalize_metric(@experiment)
@goal1 = @goals[0]
@goal2 = @goals[1]
end
it "should normalize experiment" do
expect(@experiment_name).to eq("link_color")
expect(@goals).to eq(["purchase", "refund"])
end
describe "ab_test" do
it "should allow experiment goals interface as a single hash" do
ab_test(@experiment, *@alternatives)
experiment = Split::ExperimentCatalog.find("link_color")
expect(experiment.goals).to eq(["purchase", "refund"])
end
end
describe "ab_finished" do
before do
@alternative_name = ab_test(@experiment, *@alternatives)
end
it "should increment the counter for the specified-goal completed alternative" do
expect { ab_finished({ "link_color" => ["purchase"] }) }
.to change { Split::Alternative.new(@alternative_name, @experiment_name).completed_count(@goal2) }.by(0)
.and change { Split::Alternative.new(@alternative_name, @experiment_name).completed_count(@goal1) }.by(1)
end
end
end
end
<MSG> More issues for finished(:reset => false)
When a user completes a test but reset is set to false, when they hit ab_test again they will get the control alternative. This is because doing_other_tests? was doing the same as issue #83 and counting the finished result as another experiment. This fixes that.
<DFF> @@ -177,6 +177,12 @@ describe Split::Helper do
session[:split] = nil
lambda { finished('some_experiment_not_started_by_the_user') }.should_not raise_exception
end
+
+ it 'should not be doing other tests when it has completed one that has :reset => false' do
+ ab_user[@experiment.key] = @alternative_name
+ ab_user[@experiment.finished_key] = true
+ doing_other_tests?(@experiment.key).should be false
+ end
end
describe 'conversions' do
| 6 | More issues for finished(:reset => false) | 0 | .rb | rb | mit | splitrb/split |
10071856 | <NME> helper_spec.rb
<BEF> # frozen_string_literal: true
require "spec_helper"
# TODO change some of these tests to use Rack::Test
describe Split::Helper do
include Split::Helper
let(:experiment) {
Split::ExperimentCatalog.find_or_create("link_color", "blue", "red")
}
describe "ab_test" do
it "should not raise an error when passed strings for alternatives" do
expect { ab_test("xyz", "1", "2", "3") }.not_to raise_error
end
it "should not raise an error when passed an array for alternatives" do
expect { ab_test("xyz", ["1", "2", "3"]) }.not_to raise_error
end
it "should raise the appropriate error when passed integers for alternatives" do
expect { ab_test("xyz", 1, 2, 3) }.to raise_error(ArgumentError)
end
it "should raise the appropriate error when passed symbols for alternatives" do
expect { ab_test("xyz", :a, :b, :c) }.to raise_error(ArgumentError)
end
it "should not raise error when passed an array for goals" do
expect { ab_test({ "link_color" => ["purchase", "refund"] }, "blue", "red") }.not_to raise_error
end
it "should not raise error when passed just one goal" do
expect { ab_test({ "link_color" => "purchase" }, "blue", "red") }.not_to raise_error
end
it "raises an appropriate error when processing combined expirements" do
Split.configuration.experiments = {
combined_exp_1: {
alternatives: [ { name: "control", percent: 50 }, { name: "test-alt", percent: 50 } ],
metric: :my_metric,
combined_experiments: [:combined_exp_1_sub_1]
}
}
Split::ExperimentCatalog.find_or_create("combined_exp_1")
expect { ab_test("combined_exp_1") }.to raise_error(Split::InvalidExperimentsFormatError)
end
it "should assign a random alternative to a new user when there are an equal number of alternatives assigned" do
ab_test("link_color", "blue", "red")
expect(["red", "blue"]).to include(ab_user["link_color"])
end
it "should increment the participation counter after assignment to a new user" do
previous_red_count = Split::Alternative.new("red", "link_color").participant_count
previous_blue_count = Split::Alternative.new("blue", "link_color").participant_count
ab_test("link_color", "blue", "red")
new_red_count = Split::Alternative.new("red", "link_color").participant_count
new_blue_count = Split::Alternative.new("blue", "link_color").participant_count
expect((new_red_count + new_blue_count)).to eq(previous_red_count + previous_blue_count + 1)
end
it "should not increment the counter for an experiment that the user is not participating in" do
ab_test("link_color", "blue", "red")
e = Split::ExperimentCatalog.find_or_create("button_size", "small", "big")
expect {
# User shouldn't participate in this second experiment
ab_test("button_size", "small", "big")
}.not_to change { e.participant_count }
end
it "should not increment the counter for an ended experiment" do
e = Split::ExperimentCatalog.find_or_create("button_size", "small", "big")
e.winner = "small"
expect {
a = ab_test("button_size", "small", "big")
expect(a).to eq("small")
}.not_to change { e.participant_count }
end
it "should not increment the counter for an not started experiment" do
expect(Split.configuration).to receive(:start_manually).and_return(true)
e = Split::ExperimentCatalog.find_or_create("button_size", "small", "big")
expect {
a = ab_test("button_size", "small", "big")
expect(a).to eq("small")
}.not_to change { e.participant_count }
end
it "should return the given alternative for an existing user" do
expect(ab_test("link_color", "blue", "red")).to eq ab_test("link_color", "blue", "red")
end
it "should always return the winner if one is present" do
experiment.winner = "orange"
expect(ab_test("link_color", "blue", "red")).to eq("orange")
end
it "should allow the alternative to be forced by passing it in the params" do
# ?ab_test[link_color]=blue
@params = { "ab_test" => { "link_color" => "blue" } }
alternative = ab_test("link_color", "blue", "red")
expect(alternative).to eq("blue")
alternative = ab_test("link_color", { "blue" => 1 }, "red" => 5)
expect(alternative).to eq("blue")
@params = { "ab_test" => { "link_color" => "red" } }
alternative = ab_test("link_color", "blue", "red")
expect(alternative).to eq("red")
alternative = ab_test("link_color", { "blue" => 5 }, "red" => 1)
expect(alternative).to eq("red")
end
it "should not allow an arbitrary alternative" do
@params = { "ab_test" => { "link_color" => "pink" } }
alternative = ab_test("link_color", "blue")
expect(alternative).to eq("blue")
end
it "should not store the split when a param forced alternative" do
@params = { "ab_test" => { "link_color" => "blue" } }
expect(ab_user).not_to receive(:[]=)
ab_test("link_color", "blue", "red")
end
it "SPLIT_DISABLE query parameter should also force the alternative (uses control)" do
@params = { "SPLIT_DISABLE" => "true" }
alternative = ab_test("link_color", "blue", "red")
expect(alternative).to eq("blue")
alternative = ab_test("link_color", { "blue" => 1 }, "red" => 5)
expect(alternative).to eq("blue")
alternative = ab_test("link_color", "red", "blue")
expect(alternative).to eq("red")
alternative = ab_test("link_color", { "red" => 5 }, "blue" => 1)
expect(alternative).to eq("red")
end
it "should not store the split when Split generically disabled" do
@params = { "SPLIT_DISABLE" => "true" }
expect(ab_user).not_to receive(:[]=)
ab_test("link_color", "blue", "red")
end
context "when store_override is set" do
before { Split.configuration.store_override = true }
it "should store the forced alternative" do
@params = { "ab_test" => { "link_color" => "blue" } }
expect(ab_user).to receive(:[]=).with("link_color", "blue")
ab_test("link_color", "blue", "red")
end
end
context "when on_trial_choose is set" do
before { Split.configuration.on_trial_choose = :some_method }
it "should call the method" do
expect(self).to receive(:some_method)
ab_test("link_color", "blue", "red")
end
end
it "should allow passing a block" do
alt = ab_test("link_color", "blue", "red")
ret = ab_test("link_color", "blue", "red") { |alternative| "shared/#{alternative}" }
expect(ret).to eq("shared/#{alt}")
end
session[:split] = nil
lambda { finished('some_experiment_not_started_by_the_user') }.should_not raise_exception
end
end
describe 'conversions' do
it "should only let a user participate in one experiment at a time" do
link_color = ab_test("link_color", "blue", "red")
ab_test("button_size", "small", "big")
expect(ab_user["link_color"]).to eq(link_color)
big = Split::Alternative.new("big", "button_size")
expect(big.participant_count).to eq(0)
small = Split::Alternative.new("small", "button_size")
expect(small.participant_count).to eq(0)
end
it "should let a user participate in many experiment with allow_multiple_experiments option" do
Split.configure do |config|
config.allow_multiple_experiments = true
end
link_color = ab_test("link_color", "blue", "red")
button_size = ab_test("button_size", "small", "big")
expect(ab_user["link_color"]).to eq(link_color)
expect(ab_user["button_size"]).to eq(button_size)
button_size_alt = Split::Alternative.new(button_size, "button_size")
expect(button_size_alt.participant_count).to eq(1)
end
context "with allow_multiple_experiments = 'control'" do
it "should let a user participate in many experiment with one non-'control' alternative" do
Split.configure do |config|
config.allow_multiple_experiments = "control"
end
groups = 100.times.map do |n|
ab_test("test#{n}".to_sym, { "control" => (100 - n) }, { "test#{n}-alt" => n })
end
experiments = ab_user.active_experiments
expect(experiments.size).to be > 1
count_control = experiments.values.count { |g| g == "control" }
expect(count_control).to eq(experiments.size - 1)
count_alts = groups.count { |g| g != "control" }
expect(count_alts).to eq(1)
end
context "when user already has experiment" do
let(:mock_user) { Split::User.new(self, { "test_0" => "test-alt" }) }
before do
Split.configure do |config|
config.allow_multiple_experiments = "control"
end
Split::ExperimentCatalog.find_or_initialize("test_0", "control", "test-alt").save
Split::ExperimentCatalog.find_or_initialize("test_1", "control", "test-alt").save
end
it "should restore previously selected alternative" do
expect(ab_user.active_experiments.size).to eq 1
expect(ab_test(:test_0, { "control" => 100 }, { "test-alt" => 1 })).to eq "test-alt"
expect(ab_test(:test_0, { "control" => 1 }, { "test-alt" => 100 })).to eq "test-alt"
end
it "should select the correct alternatives after experiment resets" do
experiment = Split::ExperimentCatalog.find(:test_0)
experiment.reset
mock_user[experiment.key] = "test-alt"
expect(ab_user.active_experiments.size).to eq 1
expect(ab_test(:test_0, { "control" => 100 }, { "test-alt" => 1 })).to eq "test-alt"
expect(ab_test(:test_0, { "control" => 0 }, { "test-alt" => 100 })).to eq "test-alt"
end
it "lets override existing choice" do
pending "this requires user store reset on first call not depending on whelther it is current trial"
@params = { "ab_test" => { "test_1" => "test-alt" } }
expect(ab_test(:test_0, { "control" => 0 }, { "test-alt" => 100 })).to eq "control"
expect(ab_test(:test_1, { "control" => 100 }, { "test-alt" => 1 })).to eq "test-alt"
end
end
end
it "should not over-write a finished key when an experiment is on a later version" do
experiment.increment_version
ab_user = { experiment.key => "blue", experiment.finished_key => true }
finished_session = ab_user.dup
ab_test("link_color", "blue", "red")
expect(ab_user).to eq(finished_session)
end
end
describe "metadata" do
context "is defined" do
before do
Split.configuration.experiments = {
my_experiment: {
alternatives: ["one", "two"],
resettable: false,
metadata: { "one" => "Meta1", "two" => "Meta2" }
}
}
end
it "should be passed to helper block" do
@params = { "ab_test" => { "my_experiment" => "two" } }
expect(ab_test("my_experiment")).to eq "two"
expect(ab_test("my_experiment") do |alternative, meta|
meta
end).to eq("Meta2")
end
it "should pass control metadata helper block if library disabled" do
Split.configure do |config|
config.enabled = false
end
expect(ab_test("my_experiment")).to eq "one"
expect(ab_test("my_experiment") do |_, meta|
meta
end).to eq("Meta1")
end
end
context "is not defined" do
before do
Split.configuration.experiments = {
my_experiment: {
alternatives: ["one", "two"],
resettable: false,
metadata: nil
}
}
end
it "should be passed to helper block" do
expect(ab_test("my_experiment") do |alternative, meta|
meta
end).to eq({})
end
it "should pass control metadata helper block if library disabled" do
Split.configure do |config|
config.enabled = false
end
expect(ab_test("my_experiment") do |_, meta|
meta
end).to eq({})
end
end
end
describe "ab_finished" do
context "for an experiment that the user participates in" do
before(:each) do
@experiment_name = "link_color"
@alternatives = ["blue", "red"]
@experiment = Split::ExperimentCatalog.find_or_create(@experiment_name, *@alternatives)
@alternative_name = ab_test(@experiment_name, *@alternatives)
@previous_completion_count = Split::Alternative.new(@alternative_name, @experiment_name).completed_count
end
it "should increment the counter for the completed alternative" do
ab_finished(@experiment_name)
new_completion_count = Split::Alternative.new(@alternative_name, @experiment_name).completed_count
expect(new_completion_count).to eq(@previous_completion_count + 1)
end
it "should set experiment's finished key if reset is false" do
ab_finished(@experiment_name, { reset: false })
expect(ab_user[@experiment.key]).to eq(@alternative_name)
expect(ab_user[@experiment.finished_key]).to eq(true)
end
it "should not increment the counter if reset is false and the experiment has been already finished" do
2.times { ab_finished(@experiment_name, { reset: false }) }
new_completion_count = Split::Alternative.new(@alternative_name, @experiment_name).completed_count
expect(new_completion_count).to eq(@previous_completion_count + 1)
end
it "should not increment the counter for an ended experiment" do
e = Split::ExperimentCatalog.find_or_create("button_size", "small", "big")
e.winner = "small"
a = ab_test("button_size", "small", "big")
expect(a).to eq("small")
expect {
ab_finished("button_size")
}.not_to change { Split::Alternative.new(a, "button_size").completed_count }
end
it "should clear out the user's participation from their session" do
expect(ab_user[@experiment.key]).to eq(@alternative_name)
ab_finished(@experiment_name)
expect(ab_user.keys).to be_empty
end
it "should not clear out the users session if reset is false" do
expect(ab_user[@experiment.key]).to eq(@alternative_name)
ab_finished(@experiment_name, { reset: false })
expect(ab_user[@experiment.key]).to eq(@alternative_name)
expect(ab_user[@experiment.finished_key]).to eq(true)
end
it "should reset the users session when experiment is not versioned" do
expect(ab_user[@experiment.key]).to eq(@alternative_name)
ab_finished(@experiment_name)
expect(ab_user.keys).to be_empty
end
it "should reset the users session when experiment is versioned" do
@experiment.increment_version
@alternative_name = ab_test(@experiment_name, *@alternatives)
expect(ab_user[@experiment.key]).to eq(@alternative_name)
ab_finished(@experiment_name)
expect(ab_user.keys).to be_empty
end
context "when on_trial_complete is set" do
before { Split.configuration.on_trial_complete = :some_method }
it "should call the method" do
expect(self).to receive(:some_method)
ab_finished(@experiment_name)
end
it "should not call the method without alternative" do
ab_user[@experiment.key] = nil
expect(self).not_to receive(:some_method)
ab_finished(@experiment_name)
end
end
end
context "for an experiment that the user is excluded from" do
before do
alternative = ab_test("link_color", "blue", "red")
expect(Split::Alternative.new(alternative, "link_color").participant_count).to eq(1)
alternative = ab_test("button_size", "small", "big")
expect(Split::Alternative.new(alternative, "button_size").participant_count).to eq(0)
end
it "should not increment the completed counter" do
# So, user should be participating in the link_color experiment and
# receive the control for button_size. As the user is not participating in
# the button size experiment, finishing it should not increase the
# completion count for that alternative.
expect {
ab_finished("button_size")
}.not_to change { Split::Alternative.new("small", "button_size").completed_count }
end
end
context "for an experiment that the user does not participate in" do
before do
Split::ExperimentCatalog.find_or_create(:not_started_experiment, "control", "alt")
end
it "should not raise an exception" do
expect { ab_finished(:not_started_experiment) }.not_to raise_exception
end
it "should not change the user state when reset is false" do
expect { ab_finished(:not_started_experiment, reset: false) }.not_to change { ab_user.keys }.from([])
end
it "should not change the user state when reset is true" do
expect(self).not_to receive(:reset!)
ab_finished(:not_started_experiment)
end
it "should not increment the completed counter" do
ab_finished(:not_started_experiment)
expect(Split::Alternative.new("control", :not_started_experiment).completed_count).to eq(0)
expect(Split::Alternative.new("alt", :not_started_experiment).completed_count).to eq(0)
end
end
end
context "finished with config" do
it "passes reset option" do
Split.configuration.experiments = {
my_experiment: {
alternatives: ["one", "two"],
resettable: false,
}
}
alternative = ab_test(:my_experiment)
experiment = Split::ExperimentCatalog.find :my_experiment
ab_finished :my_experiment
expect(ab_user[experiment.key]).to eq(alternative)
expect(ab_user[experiment.finished_key]).to eq(true)
end
end
context "finished with metric name" do
before { Split.configuration.experiments = {} }
before { expect(Split::Alternative).to receive(:new).at_least(1).times.and_call_original }
def should_finish_experiment(experiment_name, should_finish = true)
alts = Split.configuration.experiments[experiment_name][:alternatives]
experiment = Split::ExperimentCatalog.find_or_create(experiment_name, *alts)
alt_name = ab_user[experiment.key] = alts.first
alt = double("alternative")
expect(alt).to receive(:name).at_most(1).times.and_return(alt_name)
expect(Split::Alternative).to receive(:new).at_most(1).times.with(alt_name, experiment_name.to_s).and_return(alt)
if should_finish
expect(alt).to receive(:increment_completion).at_most(1).times
else
expect(alt).not_to receive(:increment_completion)
end
end
it "completes the test" do
Split.configuration.experiments[:my_experiment] = {
alternatives: [ "control_opt", "other_opt" ],
metric: :my_metric
}
should_finish_experiment :my_experiment
ab_finished :my_metric
end
it "completes all relevant tests" do
Split.configuration.experiments = {
exp_1: {
alternatives: [ "1-1", "1-2" ],
metric: :my_metric
},
exp_2: {
alternatives: [ "2-1", "2-2" ],
metric: :another_metric
},
exp_3: {
alternatives: [ "3-1", "3-2" ],
metric: :my_metric
},
}
should_finish_experiment :exp_1
should_finish_experiment :exp_2, false
should_finish_experiment :exp_3
ab_finished :my_metric
end
it "passes reset option" do
Split.configuration.experiments = {
my_exp: {
alternatives: ["one", "two"],
metric: :my_metric,
resettable: false,
}
}
alternative_name = ab_test(:my_exp)
exp = Split::ExperimentCatalog.find :my_exp
ab_finished :my_metric
expect(ab_user[exp.key]).to eq(alternative_name)
expect(ab_user[exp.finished_key]).to be_truthy
end
it "passes through options" do
Split.configuration.experiments = {
my_exp: {
alternatives: ["one", "two"],
metric: :my_metric,
}
}
alternative_name = ab_test(:my_exp)
exp = Split::ExperimentCatalog.find :my_exp
ab_finished :my_metric, reset: false
expect(ab_user[exp.key]).to eq(alternative_name)
expect(ab_user[exp.finished_key]).to be_truthy
end
end
describe "conversions" do
it "should return a conversion rate for an alternative" do
alternative_name = ab_test("link_color", "blue", "red")
previous_convertion_rate = Split::Alternative.new(alternative_name, "link_color").conversion_rate
expect(previous_convertion_rate).to eq(0.0)
ab_finished("link_color")
new_convertion_rate = Split::Alternative.new(alternative_name, "link_color").conversion_rate
expect(new_convertion_rate).to eq(1.0)
end
end
describe "active experiments" do
it "should show an active test" do
alternative = ab_test("def", "4", "5", "6")
expect(active_experiments.count).to eq 1
expect(active_experiments.first[0]).to eq "def"
expect(active_experiments.first[1]).to eq alternative
end
it "should show a finished test" do
alternative = ab_test("def", "4", "5", "6")
ab_finished("def", { reset: false })
expect(active_experiments.count).to eq 1
expect(active_experiments.first[0]).to eq "def"
expect(active_experiments.first[1]).to eq alternative
end
it "should show an active test when an experiment is on a later version" do
experiment.reset
expect(experiment.version).to eq(1)
ab_test("link_color", "blue", "red")
expect(active_experiments.count).to eq 1
expect(active_experiments.first[0]).to eq "link_color"
end
it "should show versioned tests properly" do
10.times { experiment.reset }
alternative = ab_test(experiment.name, "blue", "red")
ab_finished(experiment.name, reset: false)
expect(experiment.version).to eq(10)
expect(active_experiments.count).to eq 1
expect(active_experiments).to eq({ "link_color" => alternative })
end
it "should show multiple tests" do
Split.configure do |config|
config.allow_multiple_experiments = true
end
alternative = ab_test("def", "4", "5", "6")
another_alternative = ab_test("ghi", "7", "8", "9")
expect(active_experiments.count).to eq 2
expect(active_experiments["def"]).to eq alternative
expect(active_experiments["ghi"]).to eq another_alternative
end
it "should not show tests with winners" do
Split.configure do |config|
config.allow_multiple_experiments = true
end
e = Split::ExperimentCatalog.find_or_create("def", "4", "5", "6")
e.winner = "4"
ab_test("def", "4", "5", "6")
another_alternative = ab_test("ghi", "7", "8", "9")
expect(active_experiments.count).to eq 1
expect(active_experiments.first[0]).to eq "ghi"
expect(active_experiments.first[1]).to eq another_alternative
end
end
describe "when user is a robot" do
before(:each) do
@request = OpenStruct.new(user_agent: "Googlebot/2.1 (+http://www.google.com/bot.html)")
end
describe "ab_test" do
it "should return the control" do
alternative = ab_test("link_color", "blue", "red")
expect(alternative).to eq experiment.control.name
end
it "should not create a experiment" do
ab_test("link_color", "blue", "red")
expect(Split::Experiment.new("link_color")).to be_a_new_record
end
it "should not increment the participation count" do
previous_red_count = Split::Alternative.new("red", "link_color").participant_count
previous_blue_count = Split::Alternative.new("blue", "link_color").participant_count
ab_test("link_color", "blue", "red")
new_red_count = Split::Alternative.new("red", "link_color").participant_count
new_blue_count = Split::Alternative.new("blue", "link_color").participant_count
expect((new_red_count + new_blue_count)).to eq(previous_red_count + previous_blue_count)
end
end
describe "finished" do
it "should not increment the completed count" do
alternative_name = ab_test("link_color", "blue", "red")
previous_completion_count = Split::Alternative.new(alternative_name, "link_color").completed_count
ab_finished("link_color")
new_completion_count = Split::Alternative.new(alternative_name, "link_color").completed_count
expect(new_completion_count).to eq(previous_completion_count)
end
end
end
describe "when providing custom ignore logic" do
context "using a proc to configure custom logic" do
before(:each) do
Split.configure do |c|
c.ignore_filter = proc { |request| true } # ignore everything
end
end
it "ignores the ab_test" do
ab_test("link_color", "blue", "red")
red_count = Split::Alternative.new("red", "link_color").participant_count
blue_count = Split::Alternative.new("blue", "link_color").participant_count
expect((red_count + blue_count)).to be(0)
end
end
end
shared_examples_for "a disabled test" do
describe "ab_test" do
it "should return the control" do
alternative = ab_test("link_color", "blue", "red")
expect(alternative).to eq experiment.control.name
end
it "should not increment the participation count" do
previous_red_count = Split::Alternative.new("red", "link_color").participant_count
previous_blue_count = Split::Alternative.new("blue", "link_color").participant_count
ab_test("link_color", "blue", "red")
new_red_count = Split::Alternative.new("red", "link_color").participant_count
new_blue_count = Split::Alternative.new("blue", "link_color").participant_count
expect((new_red_count + new_blue_count)).to eq(previous_red_count + previous_blue_count)
end
end
describe "finished" do
it "should not increment the completed count" do
alternative_name = ab_test("link_color", "blue", "red")
previous_completion_count = Split::Alternative.new(alternative_name, "link_color").completed_count
ab_finished("link_color")
new_completion_count = Split::Alternative.new(alternative_name, "link_color").completed_count
expect(new_completion_count).to eq(previous_completion_count)
end
end
end
describe "when ip address is ignored" do
context "individually" do
before(:each) do
@request = OpenStruct.new(ip: "81.19.48.130")
Split.configure do |c|
c.ignore_ip_addresses << "81.19.48.130"
end
end
it_behaves_like "a disabled test"
end
context "for a range" do
before(:each) do
@request = OpenStruct.new(ip: "81.19.48.129")
Split.configure do |c|
c.ignore_ip_addresses << /81\.19\.48\.[0-9]+/
end
end
it_behaves_like "a disabled test"
end
context "using both a range and a specific value" do
before(:each) do
@request = OpenStruct.new(ip: "81.19.48.128")
Split.configure do |c|
c.ignore_ip_addresses << "81.19.48.130"
c.ignore_ip_addresses << /81\.19\.48\.[0-9]+/
end
end
it_behaves_like "a disabled test"
end
context "when ignored other address" do
before do
@request = OpenStruct.new(ip: "1.1.1.1")
Split.configure do |c|
c.ignore_ip_addresses << "81.19.48.130"
end
end
it "works as usual" do
alternative_name = ab_test("link_color", "red", "blue")
expect {
ab_finished("link_color")
}.to change(Split::Alternative.new(alternative_name, "link_color"), :completed_count).by(1)
end
end
end
describe "when user is previewing" do
before(:each) do
@request = OpenStruct.new(headers: { "x-purpose" => "preview" })
end
it_behaves_like "a disabled test"
end
describe "versioned experiments" do
it "should use version zero if no version is present" do
alternative_name = ab_test("link_color", "blue", "red")
expect(experiment.version).to eq(0)
expect(ab_user["link_color"]).to eq(alternative_name)
end
it "should save the version of the experiment to the session" do
experiment.reset
expect(experiment.version).to eq(1)
alternative_name = ab_test("link_color", "blue", "red")
expect(ab_user["link_color:1"]).to eq(alternative_name)
end
it "should load the experiment even if the version is not 0" do
experiment.reset
expect(experiment.version).to eq(1)
alternative_name = ab_test("link_color", "blue", "red")
expect(ab_user["link_color:1"]).to eq(alternative_name)
return_alternative_name = ab_test("link_color", "blue", "red")
expect(return_alternative_name).to eq(alternative_name)
end
it "should reset the session of a user on an older version of the experiment" do
alternative_name = ab_test("link_color", "blue", "red")
expect(ab_user["link_color"]).to eq(alternative_name)
alternative = Split::Alternative.new(alternative_name, "link_color")
expect(alternative.participant_count).to eq(1)
experiment.reset
expect(experiment.version).to eq(1)
alternative = Split::Alternative.new(alternative_name, "link_color")
expect(alternative.participant_count).to eq(0)
new_alternative_name = ab_test("link_color", "blue", "red")
expect(ab_user["link_color:1"]).to eq(new_alternative_name)
new_alternative = Split::Alternative.new(new_alternative_name, "link_color")
expect(new_alternative.participant_count).to eq(1)
end
it "should cleanup old versions of experiments from the session" do
alternative_name = ab_test("link_color", "blue", "red")
expect(ab_user["link_color"]).to eq(alternative_name)
alternative = Split::Alternative.new(alternative_name, "link_color")
expect(alternative.participant_count).to eq(1)
experiment.reset
expect(experiment.version).to eq(1)
alternative = Split::Alternative.new(alternative_name, "link_color")
expect(alternative.participant_count).to eq(0)
new_alternative_name = ab_test("link_color", "blue", "red")
expect(ab_user["link_color:1"]).to eq(new_alternative_name)
end
it "should only count completion of users on the current version" do
alternative_name = ab_test("link_color", "blue", "red")
expect(ab_user["link_color"]).to eq(alternative_name)
Split::Alternative.new(alternative_name, "link_color")
experiment.reset
expect(experiment.version).to eq(1)
ab_finished("link_color")
alternative = Split::Alternative.new(alternative_name, "link_color")
expect(alternative.completed_count).to eq(0)
end
end
context "when redis is not available" do
before(:each) do
expect(Split).to receive(:redis).at_most(5).times.and_raise(Errno::ECONNREFUSED.new)
end
context "and db_failover config option is turned off" do
before(:each) do
Split.configure do |config|
config.db_failover = false
end
end
describe "ab_test" do
it "should raise an exception" do
expect { ab_test("link_color", "blue", "red") }.to raise_error(Errno::ECONNREFUSED)
end
end
describe "finished" do
it "should raise an exception" do
expect { ab_finished("link_color") }.to raise_error(Errno::ECONNREFUSED)
end
end
describe "disable split testing" do
before(:each) do
Split.configure do |config|
config.enabled = false
end
end
it "should not attempt to connect to redis" do
expect { ab_test("link_color", "blue", "red") }.not_to raise_error
end
it "should return control variable" do
expect(ab_test("link_color", "blue", "red")).to eq("blue")
expect { ab_finished("link_color") }.not_to raise_error
end
end
end
context "and db_failover config option is turned on" do
before(:each) do
Split.configure do |config|
config.db_failover = true
end
end
describe "ab_test" do
it "should not raise an exception" do
expect { ab_test("link_color", "blue", "red") }.not_to raise_error
end
it "should call db_failover_on_db_error proc with error as parameter" do
Split.configure do |config|
config.db_failover_on_db_error = proc do |error|
expect(error).to be_a(Errno::ECONNREFUSED)
end
end
expect(Split.configuration.db_failover_on_db_error).to receive(:call).and_call_original
ab_test("link_color", "blue", "red")
end
it "should always use first alternative" do
expect(ab_test("link_color", "blue", "red")).to eq("blue")
expect(ab_test("link_color", { "blue" => 0.01 }, "red" => 0.2)).to eq("blue")
expect(ab_test("link_color", { "blue" => 0.8 }, { "red" => 20 })).to eq("blue")
expect(ab_test("link_color", "blue", "red") do |alternative|
"shared/#{alternative}"
end).to eq("shared/blue")
end
context "and db_failover_allow_parameter_override config option is turned on" do
before(:each) do
Split.configure do |config|
config.db_failover_allow_parameter_override = true
end
end
context "and given an override parameter" do
it "should use given override instead of the first alternative" do
@params = { "ab_test" => { "link_color" => "red" } }
expect(ab_test("link_color", "blue", "red")).to eq("red")
expect(ab_test("link_color", "blue", "red", "green")).to eq("red")
expect(ab_test("link_color", { "blue" => 0.01 }, "red" => 0.2)).to eq("red")
expect(ab_test("link_color", { "blue" => 0.8 }, { "red" => 20 })).to eq("red")
expect(ab_test("link_color", "blue", "red") do |alternative|
"shared/#{alternative}"
end).to eq("shared/red")
end
end
end
context "and preloaded config given" do
before do
Split.configuration.experiments[:link_color] = {
alternatives: [ "blue", "red" ],
}
end
it "uses first alternative" do
expect(ab_test(:link_color)).to eq("blue")
end
end
end
describe "finished" do
it "should not raise an exception" do
expect { ab_finished("link_color") }.not_to raise_error
end
it "should call db_failover_on_db_error proc with error as parameter" do
Split.configure do |config|
config.db_failover_on_db_error = proc do |error|
expect(error).to be_a(Errno::ECONNREFUSED)
end
end
expect(Split.configuration.db_failover_on_db_error).to receive(:call).and_call_original
ab_finished("link_color")
end
end
end
end
context "with preloaded config" do
before { Split.configuration.experiments = {} }
it "pulls options from config file" do
Split.configuration.experiments[:my_experiment] = {
alternatives: [ "control_opt", "other_opt" ],
goals: ["goal1", "goal2"]
}
ab_test :my_experiment
expect(Split::Experiment.new(:my_experiment).alternatives.map(&:name)).to eq([ "control_opt", "other_opt" ])
expect(Split::Experiment.new(:my_experiment).goals).to eq([ "goal1", "goal2" ])
end
it "can be called multiple times" do
Split.configuration.experiments[:my_experiment] = {
alternatives: [ "control_opt", "other_opt" ],
goals: ["goal1", "goal2"]
}
5.times { ab_test :my_experiment }
experiment = Split::Experiment.new(:my_experiment)
expect(experiment.alternatives.map(&:name)).to eq([ "control_opt", "other_opt" ])
expect(experiment.goals).to eq([ "goal1", "goal2" ])
expect(experiment.participant_count).to eq(1)
end
it "accepts multiple goals" do
Split.configuration.experiments[:my_experiment] = {
alternatives: [ "control_opt", "other_opt" ],
goals: [ "goal1", "goal2", "goal3" ]
}
ab_test :my_experiment
experiment = Split::Experiment.new(:my_experiment)
expect(experiment.goals).to eq([ "goal1", "goal2", "goal3" ])
end
it "allow specifying goals to be optional" do
Split.configuration.experiments[:my_experiment] = {
alternatives: [ "control_opt", "other_opt" ]
}
experiment = Split::Experiment.new(:my_experiment)
expect(experiment.goals).to eq([])
end
it "accepts multiple alternatives" do
Split.configuration.experiments[:my_experiment] = {
alternatives: [ "control_opt", "second_opt", "third_opt" ],
}
ab_test :my_experiment
experiment = Split::Experiment.new(:my_experiment)
expect(experiment.alternatives.map(&:name)).to eq([ "control_opt", "second_opt", "third_opt" ])
end
it "accepts probability on alternatives" do
Split.configuration.experiments[:my_experiment] = {
alternatives: [
{ name: "control_opt", percent: 67 },
{ name: "second_opt", percent: 10 },
{ name: "third_opt", percent: 23 },
],
}
ab_test :my_experiment
experiment = Split::Experiment.new(:my_experiment)
expect(experiment.alternatives.collect { |a| [a.name, a.weight] }).to eq([["control_opt", 0.67], ["second_opt", 0.1], ["third_opt", 0.23]])
end
it "accepts probability on some alternatives" do
Split.configuration.experiments[:my_experiment] = {
alternatives: [
{ name: "control_opt", percent: 34 },
"second_opt",
{ name: "third_opt", percent: 23 },
"fourth_opt",
],
}
ab_test :my_experiment
experiment = Split::Experiment.new(:my_experiment)
names_and_weights = experiment.alternatives.collect { |a| [a.name, a.weight] }
expect(names_and_weights).to eq([["control_opt", 0.34], ["second_opt", 0.215], ["third_opt", 0.23], ["fourth_opt", 0.215]])
expect(names_and_weights.inject(0) { |sum, nw| sum + nw[1] }).to eq(1.0)
end
it "allows name param without probability" do
Split.configuration.experiments[:my_experiment] = {
alternatives: [
{ name: "control_opt" },
"second_opt",
{ name: "third_opt", percent: 64 },
],
}
ab_test :my_experiment
experiment = Split::Experiment.new(:my_experiment)
names_and_weights = experiment.alternatives.collect { |a| [a.name, a.weight] }
expect(names_and_weights).to eq([["control_opt", 0.18], ["second_opt", 0.18], ["third_opt", 0.64]])
expect(names_and_weights.inject(0) { |sum, nw| sum + nw[1] }).to eq(1.0)
end
it "fails gracefully if config is missing experiment" do
Split.configuration.experiments = { other_experiment: { foo: "Bar" } }
expect { ab_test :my_experiment }.to raise_error(Split::ExperimentNotFound)
end
it "fails gracefully if config is missing" do
expect { Split.configuration.experiments = nil }.to raise_error(Split::InvalidExperimentsFormatError)
end
it "fails gracefully if config is missing alternatives" do
Split.configuration.experiments[:my_experiment] = { foo: "Bar" }
expect { ab_test :my_experiment }.to raise_error(NoMethodError)
end
end
it "should handle multiple experiments correctly" do
experiment2 = Split::ExperimentCatalog.find_or_create("link_color2", "blue", "red")
ab_test("link_color", "blue", "red")
ab_test("link_color2", "blue", "red")
ab_finished("link_color2")
experiment2.alternatives.each do |alt|
expect(alt.unfinished_count).to eq(0)
end
end
context "with goals" do
before do
@experiment = { "link_color" => ["purchase", "refund"] }
@alternatives = ["blue", "red"]
@experiment_name, @goals = normalize_metric(@experiment)
@goal1 = @goals[0]
@goal2 = @goals[1]
end
it "should normalize experiment" do
expect(@experiment_name).to eq("link_color")
expect(@goals).to eq(["purchase", "refund"])
end
describe "ab_test" do
it "should allow experiment goals interface as a single hash" do
ab_test(@experiment, *@alternatives)
experiment = Split::ExperimentCatalog.find("link_color")
expect(experiment.goals).to eq(["purchase", "refund"])
end
end
describe "ab_finished" do
before do
@alternative_name = ab_test(@experiment, *@alternatives)
end
it "should increment the counter for the specified-goal completed alternative" do
expect { ab_finished({ "link_color" => ["purchase"] }) }
.to change { Split::Alternative.new(@alternative_name, @experiment_name).completed_count(@goal2) }.by(0)
.and change { Split::Alternative.new(@alternative_name, @experiment_name).completed_count(@goal1) }.by(1)
end
end
end
end
<MSG> More issues for finished(:reset => false)
When a user completes a test but reset is set to false, when they hit ab_test again they will get the control alternative. This is because doing_other_tests? was doing the same as issue #83 and counting the finished result as another experiment. This fixes that.
<DFF> @@ -177,6 +177,12 @@ describe Split::Helper do
session[:split] = nil
lambda { finished('some_experiment_not_started_by_the_user') }.should_not raise_exception
end
+
+ it 'should not be doing other tests when it has completed one that has :reset => false' do
+ ab_user[@experiment.key] = @alternative_name
+ ab_user[@experiment.finished_key] = true
+ doing_other_tests?(@experiment.key).should be false
+ end
end
describe 'conversions' do
| 6 | More issues for finished(:reset => false) | 0 | .rb | rb | mit | splitrb/split |
10071857 | <NME> string-consumers.ts
<BEF> ADDFILE
<MSG> New abbreviation parser implementation
Entire abbreviation is parsed into AST, including repeater, numbering, fields etc. It will greately simplify any further abbreviation processing
<DFF> @@ -0,0 +1,208 @@
+import { strictEqual, deepStrictEqual } from 'assert';
+import Scanner from '@emmetio/scanner';
+import quoted from '../src/quoted';
+import unquoted, { AllowedChars } from '../src/unquoted';
+import expression from '../src/expression';
+import { EMString, EMNode, EMTokenGroup, EMField, EMVariable, EMRepeaterValue } from '../src/ast';
+import { AllowedTokens } from '../src/next-token';
+
+const s = (text: string) => new Scanner(text);
+const range = (node: EMNode) => [node.start, node.end];
+const wrap = (node: EMTokenGroup) => [node.before, node.after];
+
+describe('String consumers', () => {
+ describe('Quoted', () => {
+ it('basic consumer', () => {
+ let group = quoted(s('"foo"'))!;
+ strictEqual(group.tokens.length, 1);
+ deepStrictEqual(range(group), [0, 5]);
+ deepStrictEqual(wrap(group), ['"', '"']);
+
+ const token1 = group.tokens[0] as EMString;
+ strictEqual(token1.type, 'EMString');
+ strictEqual(token1.value, 'foo');
+ deepStrictEqual(range(token1), [1, 4]);
+
+ group = quoted(s('\'foo${0}${bar}$$$baz\''), AllowedTokens.FieldOrVariable | AllowedTokens.Numbering)!;
+ strictEqual(group.tokens.length, 5);
+ deepStrictEqual(range(group), [0, 21]);
+
+ const token2 = group.tokens[0] as EMString;
+ strictEqual(token2.type, 'EMString');
+ strictEqual(token2.value, 'foo');
+ deepStrictEqual(range(token2), [1, 4]);
+
+ const token3 = group.tokens[1] as EMField;
+ strictEqual(token3.type, 'EMField');
+ strictEqual(token3.index, 0);
+ strictEqual(token3.placeholder, '');
+ deepStrictEqual(range(token3), [4, 8]);
+
+ const token4 = group.tokens[2] as EMVariable;
+ strictEqual(token4.type, 'EMVariable');
+ strictEqual(token4.name, 'bar');
+ deepStrictEqual(range(token4), [8, 14]);
+
+ const token5 = group.tokens[3] as EMRepeaterValue;
+ strictEqual(token5.type, 'EMRepeaterValue');
+ strictEqual(token5.size, 3);
+ strictEqual(token5.base, 1);
+ strictEqual(token5.reverse, false);
+ deepStrictEqual(range(token5), [14, 17]);
+
+ const token6 = group.tokens[4] as EMString;
+ strictEqual(token6.type, 'EMString');
+ strictEqual(token6.value, 'baz');
+ deepStrictEqual(range(token6), [17, 20]);
+ });
+
+ it('consume escaped', () => {
+ const group = quoted(s('"foo\\$${bar}"'), AllowedTokens.Numbering)!;
+ strictEqual(group.tokens.length, 3);
+
+ const token1 = group.tokens[0] as EMString;
+ strictEqual(token1.type, 'EMString');
+ strictEqual(token1.value, 'foo$');
+ deepStrictEqual(range(token1), [1, 6]);
+
+ const token2 = group.tokens[1] as EMRepeaterValue;
+ strictEqual(token2.type, 'EMRepeaterValue');
+ strictEqual(token2.size, 1);
+ strictEqual(token2.base, 1);
+ strictEqual(token2.reverse, false);
+ deepStrictEqual(range(token2), [6, 7]);
+
+ const token3 = group.tokens[2] as EMString;
+ strictEqual(token3.type, 'EMString');
+ strictEqual(token3.value, '{bar}');
+ deepStrictEqual(range(token3), [7, 12]);
+ });
+ });
+
+ describe('Expression', () => {
+ it('basic', () => {
+ let group = expression(s('{foo bar}'))!;
+ strictEqual(group.tokens.length, 1);
+ deepStrictEqual(range(group), [0, 9]);
+ deepStrictEqual(wrap(group), ['{', '}']);
+ deepStrictEqual((group.tokens[0] as EMString).value, 'foo bar');
+ deepStrictEqual(range(group.tokens[0]), [1, 8]);
+
+ group = expression(s('{foo ${0}${bar}$$$ baz}'), AllowedTokens.FieldOrVariable | AllowedTokens.Numbering)!;
+ const token1 = group.tokens[0] as EMString;
+ strictEqual(token1.type, 'EMString');
+ strictEqual(token1.value, 'foo ');
+ deepStrictEqual(range(token1), [1, 5]);
+
+ const token2 = group.tokens[1] as EMField;
+ strictEqual(token2.type, 'EMField');
+ strictEqual(token2.index, 0);
+ strictEqual(token2.placeholder, '');
+ deepStrictEqual(range(token2), [5, 9]);
+
+ const token3 = group.tokens[2] as EMVariable;
+ strictEqual(token3.type, 'EMVariable');
+ strictEqual(token3.name, 'bar');
+ deepStrictEqual(range(token3), [9, 15]);
+
+ const token4 = group.tokens[3] as EMRepeaterValue;
+ strictEqual(token4.type, 'EMRepeaterValue');
+ strictEqual(token4.size, 3);
+ strictEqual(token4.base, 1);
+ strictEqual(token4.reverse, false);
+ deepStrictEqual(range(token4), [15, 18]);
+
+ const token5 = group.tokens[4] as EMString;
+ strictEqual(token5.type, 'EMString');
+ strictEqual(token5.value, ' baz');
+ deepStrictEqual(range(token5), [18, 22]);
+ });
+
+ it('consume escaped', () => {
+ const group = expression(s('{foo\\}${bar}}'), AllowedTokens.Numbering)!;
+ strictEqual(group.tokens.length, 3);
+
+ const token1 = group.tokens[0] as EMString;
+ strictEqual(token1.type, 'EMString');
+ strictEqual(token1.value, 'foo}');
+ deepStrictEqual(range(token1), [1, 6]);
+
+ const token2 = group.tokens[1] as EMRepeaterValue;
+ strictEqual(token2.type, 'EMRepeaterValue');
+ strictEqual(token2.size, 1);
+ strictEqual(token2.base, 1);
+ strictEqual(token2.reverse, false);
+ deepStrictEqual(range(token2), [6, 7]);
+
+ const token3 = group.tokens[2] as EMString;
+ strictEqual(token3.type, 'EMString');
+ strictEqual(token3.value, '{bar}');
+ deepStrictEqual(range(token3), [7, 12]);
+ });
+ });
+
+ describe('Unquoted', () => {
+ it('basic', () => {
+ let group = unquoted(s('foo[bar]'))!;
+ strictEqual(group.tokens.length, 1);
+ deepStrictEqual(range(group), [0, 3]);
+
+ const token1 = group.tokens[0] as EMString;
+ strictEqual(token1.type, 'EMString');
+ strictEqual(token1.value, 'foo');
+ deepStrictEqual(range(token1), [0, 3]);
+
+ group = unquoted(s('foo[bar]'), AllowedChars.Square)!;
+ strictEqual(group.tokens.length, 1);
+ deepStrictEqual(range(group), [0, 8]);
+
+ const token2 = group.tokens[0] as EMString;
+ strictEqual(token2.type, 'EMString');
+ strictEqual(token2.value, 'foo[bar]');
+ deepStrictEqual(range(token2), [0, 8]);
+
+ group = unquoted(s('foo[bar$]'), AllowedChars.Square, AllowedTokens.Numbering)!;
+ strictEqual(group.tokens.length, 3);
+ deepStrictEqual(range(group), [0, 9]);
+
+ const token3 = group.tokens[0] as EMString;
+ strictEqual(token3.type, 'EMString');
+ strictEqual(token3.value, 'foo[bar');
+ deepStrictEqual(range(token3), [0, 7]);
+
+ const token4 = group.tokens[1] as EMRepeaterValue;
+ strictEqual(token4.type, 'EMRepeaterValue');
+ strictEqual(token4.size, 1);
+ strictEqual(token4.base, 1);
+ strictEqual(token4.reverse, false);
+ deepStrictEqual(range(token4), [7, 8]);
+
+ const token5 = group.tokens[2] as EMString;
+ strictEqual(token5.type, 'EMString');
+ strictEqual(token5.value, ']');
+ deepStrictEqual(range(token5), [8, 9]);
+ });
+
+ it('consume escaped', () => {
+ const group = unquoted(s('(foo\\)${bar})'), AllowedChars.Round, AllowedTokens.Numbering)!;
+ strictEqual(group.tokens.length, 3);
+
+ const token1 = group.tokens[0] as EMString;
+ strictEqual(token1.type, 'EMString');
+ strictEqual(token1.value, '(foo)');
+ deepStrictEqual(range(token1), [0, 6]);
+
+ const token2 = group.tokens[1] as EMRepeaterValue;
+ strictEqual(token2.type, 'EMRepeaterValue');
+ strictEqual(token2.size, 1);
+ strictEqual(token2.base, 1);
+ strictEqual(token2.reverse, false);
+ deepStrictEqual(range(token2), [6, 7]);
+
+ const token3 = group.tokens[2] as EMString;
+ strictEqual(token3.type, 'EMString');
+ strictEqual(token3.value, '{bar})');
+ deepStrictEqual(range(token3), [7, 13]);
+ });
+ });
+});
| 208 | New abbreviation parser implementation | 0 | .ts | ts | mit | emmetio/emmet |
10071858 | <NME> string-consumers.ts
<BEF> ADDFILE
<MSG> New abbreviation parser implementation
Entire abbreviation is parsed into AST, including repeater, numbering, fields etc. It will greately simplify any further abbreviation processing
<DFF> @@ -0,0 +1,208 @@
+import { strictEqual, deepStrictEqual } from 'assert';
+import Scanner from '@emmetio/scanner';
+import quoted from '../src/quoted';
+import unquoted, { AllowedChars } from '../src/unquoted';
+import expression from '../src/expression';
+import { EMString, EMNode, EMTokenGroup, EMField, EMVariable, EMRepeaterValue } from '../src/ast';
+import { AllowedTokens } from '../src/next-token';
+
+const s = (text: string) => new Scanner(text);
+const range = (node: EMNode) => [node.start, node.end];
+const wrap = (node: EMTokenGroup) => [node.before, node.after];
+
+describe('String consumers', () => {
+ describe('Quoted', () => {
+ it('basic consumer', () => {
+ let group = quoted(s('"foo"'))!;
+ strictEqual(group.tokens.length, 1);
+ deepStrictEqual(range(group), [0, 5]);
+ deepStrictEqual(wrap(group), ['"', '"']);
+
+ const token1 = group.tokens[0] as EMString;
+ strictEqual(token1.type, 'EMString');
+ strictEqual(token1.value, 'foo');
+ deepStrictEqual(range(token1), [1, 4]);
+
+ group = quoted(s('\'foo${0}${bar}$$$baz\''), AllowedTokens.FieldOrVariable | AllowedTokens.Numbering)!;
+ strictEqual(group.tokens.length, 5);
+ deepStrictEqual(range(group), [0, 21]);
+
+ const token2 = group.tokens[0] as EMString;
+ strictEqual(token2.type, 'EMString');
+ strictEqual(token2.value, 'foo');
+ deepStrictEqual(range(token2), [1, 4]);
+
+ const token3 = group.tokens[1] as EMField;
+ strictEqual(token3.type, 'EMField');
+ strictEqual(token3.index, 0);
+ strictEqual(token3.placeholder, '');
+ deepStrictEqual(range(token3), [4, 8]);
+
+ const token4 = group.tokens[2] as EMVariable;
+ strictEqual(token4.type, 'EMVariable');
+ strictEqual(token4.name, 'bar');
+ deepStrictEqual(range(token4), [8, 14]);
+
+ const token5 = group.tokens[3] as EMRepeaterValue;
+ strictEqual(token5.type, 'EMRepeaterValue');
+ strictEqual(token5.size, 3);
+ strictEqual(token5.base, 1);
+ strictEqual(token5.reverse, false);
+ deepStrictEqual(range(token5), [14, 17]);
+
+ const token6 = group.tokens[4] as EMString;
+ strictEqual(token6.type, 'EMString');
+ strictEqual(token6.value, 'baz');
+ deepStrictEqual(range(token6), [17, 20]);
+ });
+
+ it('consume escaped', () => {
+ const group = quoted(s('"foo\\$${bar}"'), AllowedTokens.Numbering)!;
+ strictEqual(group.tokens.length, 3);
+
+ const token1 = group.tokens[0] as EMString;
+ strictEqual(token1.type, 'EMString');
+ strictEqual(token1.value, 'foo$');
+ deepStrictEqual(range(token1), [1, 6]);
+
+ const token2 = group.tokens[1] as EMRepeaterValue;
+ strictEqual(token2.type, 'EMRepeaterValue');
+ strictEqual(token2.size, 1);
+ strictEqual(token2.base, 1);
+ strictEqual(token2.reverse, false);
+ deepStrictEqual(range(token2), [6, 7]);
+
+ const token3 = group.tokens[2] as EMString;
+ strictEqual(token3.type, 'EMString');
+ strictEqual(token3.value, '{bar}');
+ deepStrictEqual(range(token3), [7, 12]);
+ });
+ });
+
+ describe('Expression', () => {
+ it('basic', () => {
+ let group = expression(s('{foo bar}'))!;
+ strictEqual(group.tokens.length, 1);
+ deepStrictEqual(range(group), [0, 9]);
+ deepStrictEqual(wrap(group), ['{', '}']);
+ deepStrictEqual((group.tokens[0] as EMString).value, 'foo bar');
+ deepStrictEqual(range(group.tokens[0]), [1, 8]);
+
+ group = expression(s('{foo ${0}${bar}$$$ baz}'), AllowedTokens.FieldOrVariable | AllowedTokens.Numbering)!;
+ const token1 = group.tokens[0] as EMString;
+ strictEqual(token1.type, 'EMString');
+ strictEqual(token1.value, 'foo ');
+ deepStrictEqual(range(token1), [1, 5]);
+
+ const token2 = group.tokens[1] as EMField;
+ strictEqual(token2.type, 'EMField');
+ strictEqual(token2.index, 0);
+ strictEqual(token2.placeholder, '');
+ deepStrictEqual(range(token2), [5, 9]);
+
+ const token3 = group.tokens[2] as EMVariable;
+ strictEqual(token3.type, 'EMVariable');
+ strictEqual(token3.name, 'bar');
+ deepStrictEqual(range(token3), [9, 15]);
+
+ const token4 = group.tokens[3] as EMRepeaterValue;
+ strictEqual(token4.type, 'EMRepeaterValue');
+ strictEqual(token4.size, 3);
+ strictEqual(token4.base, 1);
+ strictEqual(token4.reverse, false);
+ deepStrictEqual(range(token4), [15, 18]);
+
+ const token5 = group.tokens[4] as EMString;
+ strictEqual(token5.type, 'EMString');
+ strictEqual(token5.value, ' baz');
+ deepStrictEqual(range(token5), [18, 22]);
+ });
+
+ it('consume escaped', () => {
+ const group = expression(s('{foo\\}${bar}}'), AllowedTokens.Numbering)!;
+ strictEqual(group.tokens.length, 3);
+
+ const token1 = group.tokens[0] as EMString;
+ strictEqual(token1.type, 'EMString');
+ strictEqual(token1.value, 'foo}');
+ deepStrictEqual(range(token1), [1, 6]);
+
+ const token2 = group.tokens[1] as EMRepeaterValue;
+ strictEqual(token2.type, 'EMRepeaterValue');
+ strictEqual(token2.size, 1);
+ strictEqual(token2.base, 1);
+ strictEqual(token2.reverse, false);
+ deepStrictEqual(range(token2), [6, 7]);
+
+ const token3 = group.tokens[2] as EMString;
+ strictEqual(token3.type, 'EMString');
+ strictEqual(token3.value, '{bar}');
+ deepStrictEqual(range(token3), [7, 12]);
+ });
+ });
+
+ describe('Unquoted', () => {
+ it('basic', () => {
+ let group = unquoted(s('foo[bar]'))!;
+ strictEqual(group.tokens.length, 1);
+ deepStrictEqual(range(group), [0, 3]);
+
+ const token1 = group.tokens[0] as EMString;
+ strictEqual(token1.type, 'EMString');
+ strictEqual(token1.value, 'foo');
+ deepStrictEqual(range(token1), [0, 3]);
+
+ group = unquoted(s('foo[bar]'), AllowedChars.Square)!;
+ strictEqual(group.tokens.length, 1);
+ deepStrictEqual(range(group), [0, 8]);
+
+ const token2 = group.tokens[0] as EMString;
+ strictEqual(token2.type, 'EMString');
+ strictEqual(token2.value, 'foo[bar]');
+ deepStrictEqual(range(token2), [0, 8]);
+
+ group = unquoted(s('foo[bar$]'), AllowedChars.Square, AllowedTokens.Numbering)!;
+ strictEqual(group.tokens.length, 3);
+ deepStrictEqual(range(group), [0, 9]);
+
+ const token3 = group.tokens[0] as EMString;
+ strictEqual(token3.type, 'EMString');
+ strictEqual(token3.value, 'foo[bar');
+ deepStrictEqual(range(token3), [0, 7]);
+
+ const token4 = group.tokens[1] as EMRepeaterValue;
+ strictEqual(token4.type, 'EMRepeaterValue');
+ strictEqual(token4.size, 1);
+ strictEqual(token4.base, 1);
+ strictEqual(token4.reverse, false);
+ deepStrictEqual(range(token4), [7, 8]);
+
+ const token5 = group.tokens[2] as EMString;
+ strictEqual(token5.type, 'EMString');
+ strictEqual(token5.value, ']');
+ deepStrictEqual(range(token5), [8, 9]);
+ });
+
+ it('consume escaped', () => {
+ const group = unquoted(s('(foo\\)${bar})'), AllowedChars.Round, AllowedTokens.Numbering)!;
+ strictEqual(group.tokens.length, 3);
+
+ const token1 = group.tokens[0] as EMString;
+ strictEqual(token1.type, 'EMString');
+ strictEqual(token1.value, '(foo)');
+ deepStrictEqual(range(token1), [0, 6]);
+
+ const token2 = group.tokens[1] as EMRepeaterValue;
+ strictEqual(token2.type, 'EMRepeaterValue');
+ strictEqual(token2.size, 1);
+ strictEqual(token2.base, 1);
+ strictEqual(token2.reverse, false);
+ deepStrictEqual(range(token2), [6, 7]);
+
+ const token3 = group.tokens[2] as EMString;
+ strictEqual(token3.type, 'EMString');
+ strictEqual(token3.value, '{bar})');
+ deepStrictEqual(range(token3), [7, 13]);
+ });
+ });
+});
| 208 | New abbreviation parser implementation | 0 | .ts | ts | mit | emmetio/emmet |
10071859 | <NME> split.rb
<BEF> # frozen_string_literal: true
require "redis"
require "split/algorithms"
require "split/algorithms/block_randomization"
require "split/algorithms/weighted_sample"
require "split/algorithms/whiplash"
require "split/alternative"
require "split/cache"
require "split/configuration"
require "split/encapsulated_helper"
require "split/exceptions"
require "split/experiment"
require "split/experiment_catalog"
require "split/extensions/string"
require "split/goals_collection"
require "split/helper"
# or `Redis::Namespace`.
def redis=(server)
if server.respond_to? :split
if server =~ /redis\:\/\//
redis = Redis.connect(:url => server, :thread_safe => true)
else
server, namespace = server.split('/', 2)
require "split/zscore"
require "split/engine" if defined?(Rails)
module Split
extend self
attr_accessor :configuration
# Accepts:
# 1. A redis URL (valid for `Redis.new(url: url)`)
# 2. an options hash compatible with `Redis.new`
# 3. or a valid Redis instance (one that responds to `#smembers`). Likely,
# this will be an instance of either `Redis`, `Redis::Client`,
# `Redis::DistRedis`, or `Redis::Namespace`.
def redis=(server)
@redis = if server.is_a?(String)
Redis.new(url: server)
elsif server.is_a?(Hash)
Redis.new(server)
elsif server.respond_to?(:smembers)
server
else
raise ArgumentError,
"You must supply a url, options hash or valid Redis connection instance"
end
end
# Returns the current Redis connection. If none has been created, will
# create a new one.
def redis
return @redis if @redis
self.redis = self.configuration.redis
self.redis
end
# Call this method to modify defaults in your initializers.
#
# @example
# Split.configure do |config|
# config.ignore_ip_addresses = '192.168.2.1'
# end
def configure
self.configuration ||= Configuration.new
yield(configuration)
end
def cache(namespace, key, &block)
Split::Cache.fetch(namespace, key, &block)
end
end
# Check to see if being run in a Rails application. If so, wait until before_initialize to run configuration so Gems that create ENV variables have the chance to initialize first.
if defined?(::Rails)
class Split::Railtie < Rails::Railtie
config.before_initialize { Split.configure { } }
end
else
Split.configure { }
end
<MSG> replaced regex with string bracket search
<DFF> @@ -19,7 +19,7 @@ module Split
# or `Redis::Namespace`.
def redis=(server)
if server.respond_to? :split
- if server =~ /redis\:\/\//
+ if server["redis://"]
redis = Redis.connect(:url => server, :thread_safe => true)
else
server, namespace = server.split('/', 2)
| 1 | replaced regex with string bracket search | 1 | .rb | rb | mit | splitrb/split |
10071860 | <NME> split.rb
<BEF> # frozen_string_literal: true
require "redis"
require "split/algorithms"
require "split/algorithms/block_randomization"
require "split/algorithms/weighted_sample"
require "split/algorithms/whiplash"
require "split/alternative"
require "split/cache"
require "split/configuration"
require "split/encapsulated_helper"
require "split/exceptions"
require "split/experiment"
require "split/experiment_catalog"
require "split/extensions/string"
require "split/goals_collection"
require "split/helper"
# or `Redis::Namespace`.
def redis=(server)
if server.respond_to? :split
if server =~ /redis\:\/\//
redis = Redis.connect(:url => server, :thread_safe => true)
else
server, namespace = server.split('/', 2)
require "split/zscore"
require "split/engine" if defined?(Rails)
module Split
extend self
attr_accessor :configuration
# Accepts:
# 1. A redis URL (valid for `Redis.new(url: url)`)
# 2. an options hash compatible with `Redis.new`
# 3. or a valid Redis instance (one that responds to `#smembers`). Likely,
# this will be an instance of either `Redis`, `Redis::Client`,
# `Redis::DistRedis`, or `Redis::Namespace`.
def redis=(server)
@redis = if server.is_a?(String)
Redis.new(url: server)
elsif server.is_a?(Hash)
Redis.new(server)
elsif server.respond_to?(:smembers)
server
else
raise ArgumentError,
"You must supply a url, options hash or valid Redis connection instance"
end
end
# Returns the current Redis connection. If none has been created, will
# create a new one.
def redis
return @redis if @redis
self.redis = self.configuration.redis
self.redis
end
# Call this method to modify defaults in your initializers.
#
# @example
# Split.configure do |config|
# config.ignore_ip_addresses = '192.168.2.1'
# end
def configure
self.configuration ||= Configuration.new
yield(configuration)
end
def cache(namespace, key, &block)
Split::Cache.fetch(namespace, key, &block)
end
end
# Check to see if being run in a Rails application. If so, wait until before_initialize to run configuration so Gems that create ENV variables have the chance to initialize first.
if defined?(::Rails)
class Split::Railtie < Rails::Railtie
config.before_initialize { Split.configure { } }
end
else
Split.configure { }
end
<MSG> replaced regex with string bracket search
<DFF> @@ -19,7 +19,7 @@ module Split
# or `Redis::Namespace`.
def redis=(server)
if server.respond_to? :split
- if server =~ /redis\:\/\//
+ if server["redis://"]
redis = Redis.connect(:url => server, :thread_safe => true)
else
server, namespace = server.split('/', 2)
| 1 | replaced regex with string bracket search | 1 | .rb | rb | mit | splitrb/split |
10071861 | <NME> split.rb
<BEF> # frozen_string_literal: true
require "redis"
require "split/algorithms"
require "split/algorithms/block_randomization"
require "split/algorithms/weighted_sample"
require "split/algorithms/whiplash"
require "split/alternative"
require "split/cache"
require "split/configuration"
require "split/encapsulated_helper"
require "split/exceptions"
require "split/experiment"
require "split/experiment_catalog"
require "split/extensions/string"
require "split/goals_collection"
require "split/helper"
# or `Redis::Namespace`.
def redis=(server)
if server.respond_to? :split
if server =~ /redis\:\/\//
redis = Redis.connect(:url => server, :thread_safe => true)
else
server, namespace = server.split('/', 2)
require "split/zscore"
require "split/engine" if defined?(Rails)
module Split
extend self
attr_accessor :configuration
# Accepts:
# 1. A redis URL (valid for `Redis.new(url: url)`)
# 2. an options hash compatible with `Redis.new`
# 3. or a valid Redis instance (one that responds to `#smembers`). Likely,
# this will be an instance of either `Redis`, `Redis::Client`,
# `Redis::DistRedis`, or `Redis::Namespace`.
def redis=(server)
@redis = if server.is_a?(String)
Redis.new(url: server)
elsif server.is_a?(Hash)
Redis.new(server)
elsif server.respond_to?(:smembers)
server
else
raise ArgumentError,
"You must supply a url, options hash or valid Redis connection instance"
end
end
# Returns the current Redis connection. If none has been created, will
# create a new one.
def redis
return @redis if @redis
self.redis = self.configuration.redis
self.redis
end
# Call this method to modify defaults in your initializers.
#
# @example
# Split.configure do |config|
# config.ignore_ip_addresses = '192.168.2.1'
# end
def configure
self.configuration ||= Configuration.new
yield(configuration)
end
def cache(namespace, key, &block)
Split::Cache.fetch(namespace, key, &block)
end
end
# Check to see if being run in a Rails application. If so, wait until before_initialize to run configuration so Gems that create ENV variables have the chance to initialize first.
if defined?(::Rails)
class Split::Railtie < Rails::Railtie
config.before_initialize { Split.configure { } }
end
else
Split.configure { }
end
<MSG> replaced regex with string bracket search
<DFF> @@ -19,7 +19,7 @@ module Split
# or `Redis::Namespace`.
def redis=(server)
if server.respond_to? :split
- if server =~ /redis\:\/\//
+ if server["redis://"]
redis = Redis.connect(:url => server, :thread_safe => true)
else
server, namespace = server.split('/', 2)
| 1 | replaced regex with string bracket search | 1 | .rb | rb | mit | splitrb/split |
10071862 | <NME> split.gemspec
<BEF> # -*- encoding: utf-8 -*-
# frozen_string_literal: true
$:.push File.expand_path("../lib", __FILE__)
require "split/version"
Gem::Specification.new do |s|
s.name = "split"
s.version = Split::VERSION
s.platform = Gem::Platform::RUBY
s.authors = ["Andrew Nesbitt"]
s.licenses = ["MIT"]
s.email = ["[email protected]"]
s.homepage = "https://github.com/splitrb/split"
s.summary = "Rack based split testing framework"
s.metadata = {
"homepage_uri" => "https://github.com/splitrb/split",
"changelog_uri" => "https://github.com/splitrb/split/blob/main/CHANGELOG.md",
"source_code_uri" => "https://github.com/splitrb/split",
"bug_tracker_uri" => "https://github.com/splitrb/split/issues",
"wiki_uri" => "https://github.com/splitrb/split/wiki",
"mailing_list_uri" => "https://groups.google.com/d/forum/split-ruby"
}
s.required_ruby_version = ">= 2.5.0"
s.required_rubygems_version = ">= 2.0.0"
s.files = `git ls-files`.split("\n")
s.test_files = `git ls-files -- {test,spec,features}/*`.split("\n")
s.require_paths = ["lib"]
s.add_dependency "redis", ">= 4.2"
s.add_dependency "sinatra", ">= 1.2.6"
s.add_dependency "rubystats", ">= 0.3.0"
s.add_development_dependency "bundler", ">= 1.17"
s.add_development_dependency "simplecov", "~> 0.15"
s.add_development_dependency "rack-test", "~> 1.1"
s.add_development_dependency "rake", "~> 13"
s.add_development_dependency "rspec", "~> 3.7"
s.add_development_dependency "pry", "~> 0.10"
s.add_development_dependency "rails", ">= 5.0"
end
<MSG> Update rack-test requirement from ~> 1.1 to ~> 2.0
Updates the requirements on [rack-test](https://github.com/rack/rack-test) to permit the latest version.
- [Release notes](https://github.com/rack/rack-test/releases)
- [Changelog](https://github.com/rack/rack-test/blob/main/History.md)
- [Commits](https://github.com/rack/rack-test/compare/v1.1.0...v2.0.0)
---
updated-dependencies:
- dependency-name: rack-test
dependency-type: direct:development
...
Signed-off-by: dependabot[bot] <[email protected]>
<DFF> @@ -36,7 +36,7 @@ Gem::Specification.new do |s|
s.add_development_dependency "bundler", ">= 1.17"
s.add_development_dependency "simplecov", "~> 0.15"
- s.add_development_dependency "rack-test", "~> 1.1"
+ s.add_development_dependency "rack-test", "~> 2.0"
s.add_development_dependency "rake", "~> 13"
s.add_development_dependency "rspec", "~> 3.7"
s.add_development_dependency "pry", "~> 0.10"
| 1 | Update rack-test requirement from ~> 1.1 to ~> 2.0 | 1 | .gemspec | gemspec | mit | splitrb/split |
10071863 | <NME> split.gemspec
<BEF> # -*- encoding: utf-8 -*-
# frozen_string_literal: true
$:.push File.expand_path("../lib", __FILE__)
require "split/version"
Gem::Specification.new do |s|
s.name = "split"
s.version = Split::VERSION
s.platform = Gem::Platform::RUBY
s.authors = ["Andrew Nesbitt"]
s.licenses = ["MIT"]
s.email = ["[email protected]"]
s.homepage = "https://github.com/splitrb/split"
s.summary = "Rack based split testing framework"
s.metadata = {
"homepage_uri" => "https://github.com/splitrb/split",
"changelog_uri" => "https://github.com/splitrb/split/blob/main/CHANGELOG.md",
"source_code_uri" => "https://github.com/splitrb/split",
"bug_tracker_uri" => "https://github.com/splitrb/split/issues",
"wiki_uri" => "https://github.com/splitrb/split/wiki",
"mailing_list_uri" => "https://groups.google.com/d/forum/split-ruby"
}
s.required_ruby_version = ">= 2.5.0"
s.required_rubygems_version = ">= 2.0.0"
s.files = `git ls-files`.split("\n")
s.test_files = `git ls-files -- {test,spec,features}/*`.split("\n")
s.require_paths = ["lib"]
s.add_dependency "redis", ">= 4.2"
s.add_dependency "sinatra", ">= 1.2.6"
s.add_dependency "rubystats", ">= 0.3.0"
s.add_development_dependency "bundler", ">= 1.17"
s.add_development_dependency "simplecov", "~> 0.15"
s.add_development_dependency "rack-test", "~> 1.1"
s.add_development_dependency "rake", "~> 13"
s.add_development_dependency "rspec", "~> 3.7"
s.add_development_dependency "pry", "~> 0.10"
s.add_development_dependency "rails", ">= 5.0"
end
<MSG> Update rack-test requirement from ~> 1.1 to ~> 2.0
Updates the requirements on [rack-test](https://github.com/rack/rack-test) to permit the latest version.
- [Release notes](https://github.com/rack/rack-test/releases)
- [Changelog](https://github.com/rack/rack-test/blob/main/History.md)
- [Commits](https://github.com/rack/rack-test/compare/v1.1.0...v2.0.0)
---
updated-dependencies:
- dependency-name: rack-test
dependency-type: direct:development
...
Signed-off-by: dependabot[bot] <[email protected]>
<DFF> @@ -36,7 +36,7 @@ Gem::Specification.new do |s|
s.add_development_dependency "bundler", ">= 1.17"
s.add_development_dependency "simplecov", "~> 0.15"
- s.add_development_dependency "rack-test", "~> 1.1"
+ s.add_development_dependency "rack-test", "~> 2.0"
s.add_development_dependency "rake", "~> 13"
s.add_development_dependency "rspec", "~> 3.7"
s.add_development_dependency "pry", "~> 0.10"
| 1 | Update rack-test requirement from ~> 1.1 to ~> 2.0 | 1 | .gemspec | gemspec | mit | splitrb/split |
10071864 | <NME> split.gemspec
<BEF> # -*- encoding: utf-8 -*-
# frozen_string_literal: true
$:.push File.expand_path("../lib", __FILE__)
require "split/version"
Gem::Specification.new do |s|
s.name = "split"
s.version = Split::VERSION
s.platform = Gem::Platform::RUBY
s.authors = ["Andrew Nesbitt"]
s.licenses = ["MIT"]
s.email = ["[email protected]"]
s.homepage = "https://github.com/splitrb/split"
s.summary = "Rack based split testing framework"
s.metadata = {
"homepage_uri" => "https://github.com/splitrb/split",
"changelog_uri" => "https://github.com/splitrb/split/blob/main/CHANGELOG.md",
"source_code_uri" => "https://github.com/splitrb/split",
"bug_tracker_uri" => "https://github.com/splitrb/split/issues",
"wiki_uri" => "https://github.com/splitrb/split/wiki",
"mailing_list_uri" => "https://groups.google.com/d/forum/split-ruby"
}
s.required_ruby_version = ">= 2.5.0"
s.required_rubygems_version = ">= 2.0.0"
s.files = `git ls-files`.split("\n")
s.test_files = `git ls-files -- {test,spec,features}/*`.split("\n")
s.require_paths = ["lib"]
s.add_dependency "redis", ">= 4.2"
s.add_dependency "sinatra", ">= 1.2.6"
s.add_dependency "rubystats", ">= 0.3.0"
s.add_development_dependency "bundler", ">= 1.17"
s.add_development_dependency "simplecov", "~> 0.15"
s.add_development_dependency "rack-test", "~> 1.1"
s.add_development_dependency "rake", "~> 13"
s.add_development_dependency "rspec", "~> 3.7"
s.add_development_dependency "pry", "~> 0.10"
s.add_development_dependency "rails", ">= 5.0"
end
<MSG> Update rack-test requirement from ~> 1.1 to ~> 2.0
Updates the requirements on [rack-test](https://github.com/rack/rack-test) to permit the latest version.
- [Release notes](https://github.com/rack/rack-test/releases)
- [Changelog](https://github.com/rack/rack-test/blob/main/History.md)
- [Commits](https://github.com/rack/rack-test/compare/v1.1.0...v2.0.0)
---
updated-dependencies:
- dependency-name: rack-test
dependency-type: direct:development
...
Signed-off-by: dependabot[bot] <[email protected]>
<DFF> @@ -36,7 +36,7 @@ Gem::Specification.new do |s|
s.add_development_dependency "bundler", ">= 1.17"
s.add_development_dependency "simplecov", "~> 0.15"
- s.add_development_dependency "rack-test", "~> 1.1"
+ s.add_development_dependency "rack-test", "~> 2.0"
s.add_development_dependency "rake", "~> 13"
s.add_development_dependency "rspec", "~> 3.7"
s.add_development_dependency "pry", "~> 0.10"
| 1 | Update rack-test requirement from ~> 1.1 to ~> 2.0 | 1 | .gemspec | gemspec | mit | splitrb/split |
10071865 | <NME> expand.ts
<BEF> import { strictEqual as equal } from 'assert';
import expand, { resolveConfig } from '../src';
describe('Expand Abbreviation', () => {
describe('Markup', () => {
it('basic', () => {
equal(expand('input[value="text$"]*2'), '<input type="text" value="text1"><input type="text" value="text2">');
equal(expand('ul>.item$*2'), '<ul>\n\t<li class="item1"></li>\n\t<li class="item2"></li>\n</ul>');
// insert text into abbreviation
equal(expand('ul>.item$*', { text: ['foo', 'bar'] }), '<ul>\n\t<li class="item1">foo</li>\n\t<li class="item2">bar</li>\n</ul>');
// insert TextMate-style fields/tabstops in output
equal(expand('ul>.item$*2', {
options: {
'output.field': (index, placeholder) => `\${${index}${placeholder ? ':' + placeholder : ''}}`
}
}), '<ul>\n\t<li class="item1">${1}</li>\n\t<li class="item2">${2}</li>\n</ul>');
});
it('attributes', () => {
const snippets = {
test: 'test[!foo bar. baz={}]'
};
const opt = { snippets };
const reverse = {
options: { 'output.reverseAttributes': true },
snippets
};
equal(expand('a.test'), '<a href="" class="test"></a>');
equal(expand('a.test', reverse), '<a class="test" href=""></a>');
equal(expand('test', opt), '<test bar="bar" baz={}></test>');
equal(expand('test[foo]', opt), '<test bar="bar" baz={}></test>');
equal(expand('test[baz=a foo=1]', opt), '<test foo="1" bar="bar" baz={a}></test>');
equal(expand('map'), '<map name=""></map>');
equal(expand('map[]'), '<map name=""></map>');
equal(expand('map[name="valid"]'), '<map name="valid"></map>');
equal(expand('map[href="invalid"]'), '<map name="" href="invalid"></map>');
// Apply attributes in reverse order
equal(expand('test', reverse), '<test bar="bar" baz={}></test>');
equal(expand('test[foo]', reverse), '<test bar="bar" baz={}></test>');
equal(expand('test[baz=a foo=1]', reverse), '<test baz={a} foo="1" bar="bar"></test>');
});
it('numbering', () => {
equal(expand('ul>li.item$@-*5'), '<ul>\n\t<li class="item5"></li>\n\t<li class="item4"></li>\n\t<li class="item3"></li>\n\t<li class="item2"></li>\n\t<li class="item1"></li>\n</ul>');
});
it('syntax', () => {
equal(expand('ul>.item$*2', { syntax: 'html' }), '<ul>\n\t<li class="item1"></li>\n\t<li class="item2"></li>\n</ul>');
equal(expand('ul>.item$*2', { syntax: 'slim' }), 'ul\n\tli.item1 \n\tli.item2 ');
equal(expand('xsl:variable[name=a select=b]>div', { syntax: 'xsl' }), '<xsl:variable name="a">\n\t<div></div>\n</xsl:variable>');
});
it('custom profile', () => {
equal(expand('img'), '<img src="" alt="">');
equal(expand('img', { options: { 'output.selfClosingStyle': 'xhtml' } }), '<img src="" alt="" />');
});
it('custom variables', () => {
const variables = { charset: 'ru-RU' };
equal(expand('[charset=${charset}]{${charset}}'), '<div charset="UTF-8">UTF-8</div>');
equal(expand('[charset=${charset}]{${charset}}', { variables }), '<div charset="ru-RU">ru-RU</div>');
});
it('custom snippets', () => {
const snippets = {
link: 'link[foo=bar href]/',
foo: '.foo[bar=baz]',
repeat: 'div>ul>li{Hello World}*3'
};
equal(expand('foo', { snippets }), '<div class="foo" bar="baz"></div>');
// `link:css` depends on `link` snippet so changing it will result in
// altered `link:css` result
equal(expand('link:css'), '<link rel="stylesheet" href="style.css">');
equal(expand('link:css', { snippets }), '<link foo="bar" href="style.css">');
// https://github.com/emmetio/emmet/issues/468
equal(expand('repeat', { snippets }), '<div>\n\t<ul>\n\t\t<li>Hello World</li>\n\t\t<li>Hello World</li>\n\t\t<li>Hello World</li>\n\t</ul>\n</div>');
});
it('formatter options', () => {
equal(expand('ul>.item$*2'), '<ul>\n\t<li class="item1"></li>\n\t<li class="item2"></li>\n</ul>');
equal(expand('ul>.item$*2', { options: { 'comment.enabled': true } }),
'<ul>\n\t<li class="item1"></li>\n\t<!-- /.item1 -->\n\t<li class="item2"></li>\n\t<!-- /.item2 -->\n</ul>');
equal(expand('div>p'), '<div>\n\t<p></p>\n</div>');
equal(expand('div>p', { options: { 'output.formatLeafNode': true } }), '<div>\n\t<p>\n\t\t\n\t</p>\n</div>');
});
it('JSX', () => {
const config = { syntax: 'jsx' };
equal(expand('div#foo.bar', config), '<div id="foo" className="bar"></div>');
equal(expand('label[for=a]', config), '<label htmlFor="a"></label>');
equal(expand('Foo.Bar', config), '<Foo.Bar></Foo.Bar>');
equal(expand('div.{theme.style}', config), '<div className={theme.style}></div>');
equal(expand('p', { text: 'foo\nbar'}), '<p>\n\tfoo\n\tbar\n</p>');
equal(expand('p', { text: '<div>foo</div>'}), '<p>\n\t<div>foo</div>\n</p>');
equal(expand('p', { text: '<span>foo</span>'}), '<p><span>foo</span></p>');
});
// it.only('debug', () => {
equal(expand('.foo', { syntax: 'vue' }), '<div class="foo"></div>');
equal(expand('..foo', { syntax: 'vue' }), '<div :class="foo"></div>');
});
it('wrap with abbreviation', () => {
equal(expand('div>ul', { text: ['<div>line1</div>\n<div>line2</div>'] }),
'<div>\n\t<ul>\n\t\t<div>line1</div>\n\t\t<div>line2</div>\n\t</ul>\n</div>');
equal(expand('p', { text: 'foo\nbar' }), '<p>\n\tfoo\n\tbar\n</p>');
equal(expand('p', { text: '<div>foo</div>' }), '<p>\n\t<div>foo</div>\n</p>');
equal(expand('p', { text: '<span>foo</span>' }), '<p><span>foo</span></p>');
equal(expand('p', { text: 'foo<span>foo</span>' }), '<p>foo<span>foo</span></p>');
equal(expand('p', { text: 'foo<div>foo</div>' }), '<p>foo<div>foo</div></p>');
});
it('wrap with abbreviation href', () => {
equal(expand('a', { text: ['www.google.it'] }), '<a href="http://www.google.it">www.google.it</a>');
equal(expand('a', { text: ['then www.google.it'] }), '<a href="">then www.google.it</a>');
equal(expand('a', { text: ['www.google.it'], options: { 'markup.href': false } }), '<a href="">www.google.it</a>');
equal(expand('map[name="https://example.com"]', { text: ['some text'] }),
'<map name="https://example.com">some text</map>');
equal(expand('map[href="https://example.com"]', { text: ['some text'] }),
'<map name="" href="https://example.com">some text</map>');
equal(expand('map[name="https://example.com"]>b', { text: ['some text'] }),
'<map name="https://example.com"><b>some text</b></map>');
equal(expand('a[href="https://example.com"]>b', { text: ['<u>some text false</u>'], options: { 'markup.href': false } }),
'<a href="https://example.com"><b><u>some text false</u></b></a>');
equal(expand('a[href="https://example.com"]>b', { text: ['<u>some text true</u>'], options: { 'markup.href': true } }),
'<a href="https://example.com"><b><u>some text true</u></b></a>');
equal(expand('a[href="https://example.com"]>div', { text: ['<p>some text false</p>'], options: { 'markup.href': false } }),
'<a href="https://example.com">\n\t<div>\n\t\t<p>some text false</p>\n\t</div>\n</a>');
equal(expand('a[href="https://example.com"]>div', { text: ['<p>some text true</p>'], options: { 'markup.href': true } }),
'<a href="https://example.com">\n\t<div>\n\t\t<p>some text true</p>\n\t</div>\n</a>');
});
// it.only('debug', () => {
// equal(expand('link:css'), '<link rel="stylesheet" href="style.css">');
// });
});
describe('Pug templates', () => {
const config = resolveConfig({ syntax: 'pug' });
it('basic', () => {
equal(expand('!', config), 'doctype html\nhtml(lang="en")\n\thead\n\t\tmeta(charset="UTF-8")\n\t\tmeta(http-equiv="X-UA-Compatible", content="IE=edge")\n\t\tmeta(name="viewport", content="width=device-width, initial-scale=1.0")\n\t\ttitle Document\n\tbody ');
});
});
});
<MSG> Fix some more cases for #620 (#622)
<DFF> @@ -104,6 +104,8 @@ describe('Expand Abbreviation', () => {
equal(expand('p', { text: 'foo\nbar'}), '<p>\n\tfoo\n\tbar\n</p>');
equal(expand('p', { text: '<div>foo</div>'}), '<p>\n\t<div>foo</div>\n</p>');
equal(expand('p', { text: '<span>foo</span>'}), '<p><span>foo</span></p>');
+ equal(expand('p', { text: 'foo<span>foo</span>'}), '<p>foo<span>foo</span></p>');
+ equal(expand('p', { text: 'foo<div>foo</div>'}), '<p>foo<div>foo</div></p>');
});
// it.only('debug', () => {
| 2 | Fix some more cases for #620 (#622) | 0 | .ts | ts | mit | emmetio/emmet |
10071866 | <NME> expand.ts
<BEF> import { strictEqual as equal } from 'assert';
import expand, { resolveConfig } from '../src';
describe('Expand Abbreviation', () => {
describe('Markup', () => {
it('basic', () => {
equal(expand('input[value="text$"]*2'), '<input type="text" value="text1"><input type="text" value="text2">');
equal(expand('ul>.item$*2'), '<ul>\n\t<li class="item1"></li>\n\t<li class="item2"></li>\n</ul>');
// insert text into abbreviation
equal(expand('ul>.item$*', { text: ['foo', 'bar'] }), '<ul>\n\t<li class="item1">foo</li>\n\t<li class="item2">bar</li>\n</ul>');
// insert TextMate-style fields/tabstops in output
equal(expand('ul>.item$*2', {
options: {
'output.field': (index, placeholder) => `\${${index}${placeholder ? ':' + placeholder : ''}}`
}
}), '<ul>\n\t<li class="item1">${1}</li>\n\t<li class="item2">${2}</li>\n</ul>');
});
it('attributes', () => {
const snippets = {
test: 'test[!foo bar. baz={}]'
};
const opt = { snippets };
const reverse = {
options: { 'output.reverseAttributes': true },
snippets
};
equal(expand('a.test'), '<a href="" class="test"></a>');
equal(expand('a.test', reverse), '<a class="test" href=""></a>');
equal(expand('test', opt), '<test bar="bar" baz={}></test>');
equal(expand('test[foo]', opt), '<test bar="bar" baz={}></test>');
equal(expand('test[baz=a foo=1]', opt), '<test foo="1" bar="bar" baz={a}></test>');
equal(expand('map'), '<map name=""></map>');
equal(expand('map[]'), '<map name=""></map>');
equal(expand('map[name="valid"]'), '<map name="valid"></map>');
equal(expand('map[href="invalid"]'), '<map name="" href="invalid"></map>');
// Apply attributes in reverse order
equal(expand('test', reverse), '<test bar="bar" baz={}></test>');
equal(expand('test[foo]', reverse), '<test bar="bar" baz={}></test>');
equal(expand('test[baz=a foo=1]', reverse), '<test baz={a} foo="1" bar="bar"></test>');
});
it('numbering', () => {
equal(expand('ul>li.item$@-*5'), '<ul>\n\t<li class="item5"></li>\n\t<li class="item4"></li>\n\t<li class="item3"></li>\n\t<li class="item2"></li>\n\t<li class="item1"></li>\n</ul>');
});
it('syntax', () => {
equal(expand('ul>.item$*2', { syntax: 'html' }), '<ul>\n\t<li class="item1"></li>\n\t<li class="item2"></li>\n</ul>');
equal(expand('ul>.item$*2', { syntax: 'slim' }), 'ul\n\tli.item1 \n\tli.item2 ');
equal(expand('xsl:variable[name=a select=b]>div', { syntax: 'xsl' }), '<xsl:variable name="a">\n\t<div></div>\n</xsl:variable>');
});
it('custom profile', () => {
equal(expand('img'), '<img src="" alt="">');
equal(expand('img', { options: { 'output.selfClosingStyle': 'xhtml' } }), '<img src="" alt="" />');
});
it('custom variables', () => {
const variables = { charset: 'ru-RU' };
equal(expand('[charset=${charset}]{${charset}}'), '<div charset="UTF-8">UTF-8</div>');
equal(expand('[charset=${charset}]{${charset}}', { variables }), '<div charset="ru-RU">ru-RU</div>');
});
it('custom snippets', () => {
const snippets = {
link: 'link[foo=bar href]/',
foo: '.foo[bar=baz]',
repeat: 'div>ul>li{Hello World}*3'
};
equal(expand('foo', { snippets }), '<div class="foo" bar="baz"></div>');
// `link:css` depends on `link` snippet so changing it will result in
// altered `link:css` result
equal(expand('link:css'), '<link rel="stylesheet" href="style.css">');
equal(expand('link:css', { snippets }), '<link foo="bar" href="style.css">');
// https://github.com/emmetio/emmet/issues/468
equal(expand('repeat', { snippets }), '<div>\n\t<ul>\n\t\t<li>Hello World</li>\n\t\t<li>Hello World</li>\n\t\t<li>Hello World</li>\n\t</ul>\n</div>');
});
it('formatter options', () => {
equal(expand('ul>.item$*2'), '<ul>\n\t<li class="item1"></li>\n\t<li class="item2"></li>\n</ul>');
equal(expand('ul>.item$*2', { options: { 'comment.enabled': true } }),
'<ul>\n\t<li class="item1"></li>\n\t<!-- /.item1 -->\n\t<li class="item2"></li>\n\t<!-- /.item2 -->\n</ul>');
equal(expand('div>p'), '<div>\n\t<p></p>\n</div>');
equal(expand('div>p', { options: { 'output.formatLeafNode': true } }), '<div>\n\t<p>\n\t\t\n\t</p>\n</div>');
});
it('JSX', () => {
const config = { syntax: 'jsx' };
equal(expand('div#foo.bar', config), '<div id="foo" className="bar"></div>');
equal(expand('label[for=a]', config), '<label htmlFor="a"></label>');
equal(expand('Foo.Bar', config), '<Foo.Bar></Foo.Bar>');
equal(expand('div.{theme.style}', config), '<div className={theme.style}></div>');
equal(expand('p', { text: 'foo\nbar'}), '<p>\n\tfoo\n\tbar\n</p>');
equal(expand('p', { text: '<div>foo</div>'}), '<p>\n\t<div>foo</div>\n</p>');
equal(expand('p', { text: '<span>foo</span>'}), '<p><span>foo</span></p>');
});
// it.only('debug', () => {
equal(expand('.foo', { syntax: 'vue' }), '<div class="foo"></div>');
equal(expand('..foo', { syntax: 'vue' }), '<div :class="foo"></div>');
});
it('wrap with abbreviation', () => {
equal(expand('div>ul', { text: ['<div>line1</div>\n<div>line2</div>'] }),
'<div>\n\t<ul>\n\t\t<div>line1</div>\n\t\t<div>line2</div>\n\t</ul>\n</div>');
equal(expand('p', { text: 'foo\nbar' }), '<p>\n\tfoo\n\tbar\n</p>');
equal(expand('p', { text: '<div>foo</div>' }), '<p>\n\t<div>foo</div>\n</p>');
equal(expand('p', { text: '<span>foo</span>' }), '<p><span>foo</span></p>');
equal(expand('p', { text: 'foo<span>foo</span>' }), '<p>foo<span>foo</span></p>');
equal(expand('p', { text: 'foo<div>foo</div>' }), '<p>foo<div>foo</div></p>');
});
it('wrap with abbreviation href', () => {
equal(expand('a', { text: ['www.google.it'] }), '<a href="http://www.google.it">www.google.it</a>');
equal(expand('a', { text: ['then www.google.it'] }), '<a href="">then www.google.it</a>');
equal(expand('a', { text: ['www.google.it'], options: { 'markup.href': false } }), '<a href="">www.google.it</a>');
equal(expand('map[name="https://example.com"]', { text: ['some text'] }),
'<map name="https://example.com">some text</map>');
equal(expand('map[href="https://example.com"]', { text: ['some text'] }),
'<map name="" href="https://example.com">some text</map>');
equal(expand('map[name="https://example.com"]>b', { text: ['some text'] }),
'<map name="https://example.com"><b>some text</b></map>');
equal(expand('a[href="https://example.com"]>b', { text: ['<u>some text false</u>'], options: { 'markup.href': false } }),
'<a href="https://example.com"><b><u>some text false</u></b></a>');
equal(expand('a[href="https://example.com"]>b', { text: ['<u>some text true</u>'], options: { 'markup.href': true } }),
'<a href="https://example.com"><b><u>some text true</u></b></a>');
equal(expand('a[href="https://example.com"]>div', { text: ['<p>some text false</p>'], options: { 'markup.href': false } }),
'<a href="https://example.com">\n\t<div>\n\t\t<p>some text false</p>\n\t</div>\n</a>');
equal(expand('a[href="https://example.com"]>div', { text: ['<p>some text true</p>'], options: { 'markup.href': true } }),
'<a href="https://example.com">\n\t<div>\n\t\t<p>some text true</p>\n\t</div>\n</a>');
});
// it.only('debug', () => {
// equal(expand('link:css'), '<link rel="stylesheet" href="style.css">');
// });
});
describe('Pug templates', () => {
const config = resolveConfig({ syntax: 'pug' });
it('basic', () => {
equal(expand('!', config), 'doctype html\nhtml(lang="en")\n\thead\n\t\tmeta(charset="UTF-8")\n\t\tmeta(http-equiv="X-UA-Compatible", content="IE=edge")\n\t\tmeta(name="viewport", content="width=device-width, initial-scale=1.0")\n\t\ttitle Document\n\tbody ');
});
});
});
<MSG> Fix some more cases for #620 (#622)
<DFF> @@ -104,6 +104,8 @@ describe('Expand Abbreviation', () => {
equal(expand('p', { text: 'foo\nbar'}), '<p>\n\tfoo\n\tbar\n</p>');
equal(expand('p', { text: '<div>foo</div>'}), '<p>\n\t<div>foo</div>\n</p>');
equal(expand('p', { text: '<span>foo</span>'}), '<p><span>foo</span></p>');
+ equal(expand('p', { text: 'foo<span>foo</span>'}), '<p>foo<span>foo</span></p>');
+ equal(expand('p', { text: 'foo<div>foo</div>'}), '<p>foo<div>foo</div></p>');
});
// it.only('debug', () => {
| 2 | Fix some more cases for #620 (#622) | 0 | .ts | ts | mit | emmetio/emmet |
10071867 | <NME> helper.rb
<BEF> # frozen_string_literal: true
module Split
module Helper
OVERRIDE_PARAM_NAME = "ab_test"
module_function
def ab_test(metric_descriptor, control = nil, *alternatives)
begin
experiment = ExperimentCatalog.find_or_initialize(metric_descriptor, control, *alternatives)
alternative = if Split.configuration.enabled && !exclude_visitor?
experiment.save
raise(Split::InvalidExperimentsFormatError) unless (Split.configuration.experiments || {}).fetch(experiment.name.to_sym, {})[:combined_experiments].nil?
trial = Trial.new(user: ab_user, experiment: experiment,
else
control_variable(experiment.control)
end
rescue Errno::ECONNREFUSED, Redis::CannotConnectError => e
raise(e) unless Split.configuration.db_failover
Split.configuration.db_failover_on_db_error.call(e)
rescue Errno::ECONNREFUSED, Redis::BaseError, SocketError => e
raise(e) unless Split.configuration.db_failover
Split.configuration.db_failover_on_db_error.call(e)
if Split.configuration.db_failover_allow_parameter_override
alternative = override_alternative(experiment.name) if override_present?(experiment.name)
alternative = control_variable(experiment.control) if split_generically_disabled?
end
ensure
alternative ||= control_variable(experiment.control)
end
if block_given?
metadata = experiment.metadata[alternative] if experiment.metadata
yield(alternative, metadata || {})
else
alternative
end
end
def reset!(experiment)
ab_user.delete(experiment.key)
end
def finish_experiment(experiment, options = { reset: true })
return false if active_experiments[experiment.name].nil?
return true if experiment.has_winner?
should_reset = experiment.resettable? && options[:reset]
if ab_user[experiment.finished_key] && !should_reset
true
else
alternative_name = ab_user[experiment.key]
trial = Trial.new(
user: ab_user,
experiment: experiment,
alternative: alternative_name,
goals: options[:goals],
)
trial.complete!(self)
if should_reset
reset!(experiment)
else
ab_user[experiment.finished_key] = true
end
end
end
def ab_finished(metric_descriptor, options = { reset: true })
return if exclude_visitor? || Split.configuration.disabled?
metric_descriptor, goals = normalize_metric(metric_descriptor)
experiments = Metric.possible_experiments(metric_descriptor)
if experiments.any?
experiments.each do |experiment|
next if override_present?(experiment.key)
finish_experiment(experiment, options.merge(goals: goals))
end
end
rescue => e
raise unless Split.configuration.db_failover
Split.configuration.db_failover_on_db_error.call(e)
end
def ab_record_extra_info(metric_descriptor, key, value = 1)
return if exclude_visitor? || Split.configuration.disabled?
metric_descriptor, _ = normalize_metric(metric_descriptor)
experiments = Metric.possible_experiments(metric_descriptor)
if experiments.any?
experiments.each do |experiment|
alternative_name = ab_user[experiment.key]
if alternative_name
alternative = experiment.alternatives.find { |alt| alt.name == alternative_name }
alternative.record_extra_info(key, value) if alternative
end
end
end
rescue => e
raise unless Split.configuration.db_failover
Split.configuration.db_failover_on_db_error.call(e)
end
def ab_active_experiments
ab_user.active_experiments
rescue => e
raise unless Split.configuration.db_failover
Split.configuration.db_failover_on_db_error.call(e)
end
def override_present?(experiment_name)
override_alternative_by_params(experiment_name) || override_alternative_by_cookies(experiment_name)
end
def override_alternative(experiment_name)
override_alternative_by_params(experiment_name) || override_alternative_by_cookies(experiment_name)
end
def override_alternative_by_params(experiment_name)
defined?(params) && params[OVERRIDE_PARAM_NAME] && params[OVERRIDE_PARAM_NAME][experiment_name]
end
def override_alternative_by_cookies(experiment_name)
return unless defined?(request)
if request.cookies && request.cookies.key?("split_override")
experiments = JSON.parse(request.cookies["split_override"]) rescue {}
experiments[experiment_name]
end
end
def split_generically_disabled?
defined?(params) && params["SPLIT_DISABLE"]
end
def ab_user
@ab_user ||= User.new(self)
end
def exclude_visitor?
defined?(request) && (instance_exec(request, &Split.configuration.ignore_filter) || is_ignored_ip_address? || is_robot? || is_preview?)
end
def is_robot?
defined?(request) && request.user_agent =~ Split.configuration.robot_regex
end
def is_preview?
defined?(request) && defined?(request.headers) && request.headers["x-purpose"] == "preview"
end
def is_ignored_ip_address?
return false if Split.configuration.ignore_ip_addresses.empty?
Split.configuration.ignore_ip_addresses.each do |ip|
return true if defined?(request) && (request.ip == ip || (ip.class == Regexp && request.ip =~ ip))
end
false
end
def active_experiments
ab_user.active_experiments
end
def normalize_metric(metric_descriptor)
if Hash === metric_descriptor
experiment_name = metric_descriptor.keys.first
goals = Array(metric_descriptor.values.first)
else
experiment_name = metric_descriptor
goals = []
end
return experiment_name, goals
end
def control_variable(control)
Hash === control ? control.keys.first.to_s : control.to_s
end
end
end
<MSG> Merge pull request #310 from fusion2004/handle-dns-resolving-errors
If the DNS resolution fails for your redis server, ruby will throw a SocketError, which is currently not rescued by the ab_test helper
<DFF> @@ -16,7 +16,7 @@ module Split
else
control_variable(experiment.control)
end
- rescue Errno::ECONNREFUSED, Redis::CannotConnectError => e
+ rescue Errno::ECONNREFUSED, Redis::CannotConnectError, SocketError => e
raise(e) unless Split.configuration.db_failover
Split.configuration.db_failover_on_db_error.call(e)
| 1 | Merge pull request #310 from fusion2004/handle-dns-resolving-errors | 1 | .rb | rb | mit | splitrb/split |
10071868 | <NME> helper.rb
<BEF> # frozen_string_literal: true
module Split
module Helper
OVERRIDE_PARAM_NAME = "ab_test"
module_function
def ab_test(metric_descriptor, control = nil, *alternatives)
begin
experiment = ExperimentCatalog.find_or_initialize(metric_descriptor, control, *alternatives)
alternative = if Split.configuration.enabled && !exclude_visitor?
experiment.save
raise(Split::InvalidExperimentsFormatError) unless (Split.configuration.experiments || {}).fetch(experiment.name.to_sym, {})[:combined_experiments].nil?
trial = Trial.new(user: ab_user, experiment: experiment,
else
control_variable(experiment.control)
end
rescue Errno::ECONNREFUSED, Redis::CannotConnectError => e
raise(e) unless Split.configuration.db_failover
Split.configuration.db_failover_on_db_error.call(e)
rescue Errno::ECONNREFUSED, Redis::BaseError, SocketError => e
raise(e) unless Split.configuration.db_failover
Split.configuration.db_failover_on_db_error.call(e)
if Split.configuration.db_failover_allow_parameter_override
alternative = override_alternative(experiment.name) if override_present?(experiment.name)
alternative = control_variable(experiment.control) if split_generically_disabled?
end
ensure
alternative ||= control_variable(experiment.control)
end
if block_given?
metadata = experiment.metadata[alternative] if experiment.metadata
yield(alternative, metadata || {})
else
alternative
end
end
def reset!(experiment)
ab_user.delete(experiment.key)
end
def finish_experiment(experiment, options = { reset: true })
return false if active_experiments[experiment.name].nil?
return true if experiment.has_winner?
should_reset = experiment.resettable? && options[:reset]
if ab_user[experiment.finished_key] && !should_reset
true
else
alternative_name = ab_user[experiment.key]
trial = Trial.new(
user: ab_user,
experiment: experiment,
alternative: alternative_name,
goals: options[:goals],
)
trial.complete!(self)
if should_reset
reset!(experiment)
else
ab_user[experiment.finished_key] = true
end
end
end
def ab_finished(metric_descriptor, options = { reset: true })
return if exclude_visitor? || Split.configuration.disabled?
metric_descriptor, goals = normalize_metric(metric_descriptor)
experiments = Metric.possible_experiments(metric_descriptor)
if experiments.any?
experiments.each do |experiment|
next if override_present?(experiment.key)
finish_experiment(experiment, options.merge(goals: goals))
end
end
rescue => e
raise unless Split.configuration.db_failover
Split.configuration.db_failover_on_db_error.call(e)
end
def ab_record_extra_info(metric_descriptor, key, value = 1)
return if exclude_visitor? || Split.configuration.disabled?
metric_descriptor, _ = normalize_metric(metric_descriptor)
experiments = Metric.possible_experiments(metric_descriptor)
if experiments.any?
experiments.each do |experiment|
alternative_name = ab_user[experiment.key]
if alternative_name
alternative = experiment.alternatives.find { |alt| alt.name == alternative_name }
alternative.record_extra_info(key, value) if alternative
end
end
end
rescue => e
raise unless Split.configuration.db_failover
Split.configuration.db_failover_on_db_error.call(e)
end
def ab_active_experiments
ab_user.active_experiments
rescue => e
raise unless Split.configuration.db_failover
Split.configuration.db_failover_on_db_error.call(e)
end
def override_present?(experiment_name)
override_alternative_by_params(experiment_name) || override_alternative_by_cookies(experiment_name)
end
def override_alternative(experiment_name)
override_alternative_by_params(experiment_name) || override_alternative_by_cookies(experiment_name)
end
def override_alternative_by_params(experiment_name)
defined?(params) && params[OVERRIDE_PARAM_NAME] && params[OVERRIDE_PARAM_NAME][experiment_name]
end
def override_alternative_by_cookies(experiment_name)
return unless defined?(request)
if request.cookies && request.cookies.key?("split_override")
experiments = JSON.parse(request.cookies["split_override"]) rescue {}
experiments[experiment_name]
end
end
def split_generically_disabled?
defined?(params) && params["SPLIT_DISABLE"]
end
def ab_user
@ab_user ||= User.new(self)
end
def exclude_visitor?
defined?(request) && (instance_exec(request, &Split.configuration.ignore_filter) || is_ignored_ip_address? || is_robot? || is_preview?)
end
def is_robot?
defined?(request) && request.user_agent =~ Split.configuration.robot_regex
end
def is_preview?
defined?(request) && defined?(request.headers) && request.headers["x-purpose"] == "preview"
end
def is_ignored_ip_address?
return false if Split.configuration.ignore_ip_addresses.empty?
Split.configuration.ignore_ip_addresses.each do |ip|
return true if defined?(request) && (request.ip == ip || (ip.class == Regexp && request.ip =~ ip))
end
false
end
def active_experiments
ab_user.active_experiments
end
def normalize_metric(metric_descriptor)
if Hash === metric_descriptor
experiment_name = metric_descriptor.keys.first
goals = Array(metric_descriptor.values.first)
else
experiment_name = metric_descriptor
goals = []
end
return experiment_name, goals
end
def control_variable(control)
Hash === control ? control.keys.first.to_s : control.to_s
end
end
end
<MSG> Merge pull request #310 from fusion2004/handle-dns-resolving-errors
If the DNS resolution fails for your redis server, ruby will throw a SocketError, which is currently not rescued by the ab_test helper
<DFF> @@ -16,7 +16,7 @@ module Split
else
control_variable(experiment.control)
end
- rescue Errno::ECONNREFUSED, Redis::CannotConnectError => e
+ rescue Errno::ECONNREFUSED, Redis::CannotConnectError, SocketError => e
raise(e) unless Split.configuration.db_failover
Split.configuration.db_failover_on_db_error.call(e)
| 1 | Merge pull request #310 from fusion2004/handle-dns-resolving-errors | 1 | .rb | rb | mit | splitrb/split |
10071869 | <NME> helper.rb
<BEF> # frozen_string_literal: true
module Split
module Helper
OVERRIDE_PARAM_NAME = "ab_test"
module_function
def ab_test(metric_descriptor, control = nil, *alternatives)
begin
experiment = ExperimentCatalog.find_or_initialize(metric_descriptor, control, *alternatives)
alternative = if Split.configuration.enabled && !exclude_visitor?
experiment.save
raise(Split::InvalidExperimentsFormatError) unless (Split.configuration.experiments || {}).fetch(experiment.name.to_sym, {})[:combined_experiments].nil?
trial = Trial.new(user: ab_user, experiment: experiment,
else
control_variable(experiment.control)
end
rescue Errno::ECONNREFUSED, Redis::CannotConnectError => e
raise(e) unless Split.configuration.db_failover
Split.configuration.db_failover_on_db_error.call(e)
rescue Errno::ECONNREFUSED, Redis::BaseError, SocketError => e
raise(e) unless Split.configuration.db_failover
Split.configuration.db_failover_on_db_error.call(e)
if Split.configuration.db_failover_allow_parameter_override
alternative = override_alternative(experiment.name) if override_present?(experiment.name)
alternative = control_variable(experiment.control) if split_generically_disabled?
end
ensure
alternative ||= control_variable(experiment.control)
end
if block_given?
metadata = experiment.metadata[alternative] if experiment.metadata
yield(alternative, metadata || {})
else
alternative
end
end
def reset!(experiment)
ab_user.delete(experiment.key)
end
def finish_experiment(experiment, options = { reset: true })
return false if active_experiments[experiment.name].nil?
return true if experiment.has_winner?
should_reset = experiment.resettable? && options[:reset]
if ab_user[experiment.finished_key] && !should_reset
true
else
alternative_name = ab_user[experiment.key]
trial = Trial.new(
user: ab_user,
experiment: experiment,
alternative: alternative_name,
goals: options[:goals],
)
trial.complete!(self)
if should_reset
reset!(experiment)
else
ab_user[experiment.finished_key] = true
end
end
end
def ab_finished(metric_descriptor, options = { reset: true })
return if exclude_visitor? || Split.configuration.disabled?
metric_descriptor, goals = normalize_metric(metric_descriptor)
experiments = Metric.possible_experiments(metric_descriptor)
if experiments.any?
experiments.each do |experiment|
next if override_present?(experiment.key)
finish_experiment(experiment, options.merge(goals: goals))
end
end
rescue => e
raise unless Split.configuration.db_failover
Split.configuration.db_failover_on_db_error.call(e)
end
def ab_record_extra_info(metric_descriptor, key, value = 1)
return if exclude_visitor? || Split.configuration.disabled?
metric_descriptor, _ = normalize_metric(metric_descriptor)
experiments = Metric.possible_experiments(metric_descriptor)
if experiments.any?
experiments.each do |experiment|
alternative_name = ab_user[experiment.key]
if alternative_name
alternative = experiment.alternatives.find { |alt| alt.name == alternative_name }
alternative.record_extra_info(key, value) if alternative
end
end
end
rescue => e
raise unless Split.configuration.db_failover
Split.configuration.db_failover_on_db_error.call(e)
end
def ab_active_experiments
ab_user.active_experiments
rescue => e
raise unless Split.configuration.db_failover
Split.configuration.db_failover_on_db_error.call(e)
end
def override_present?(experiment_name)
override_alternative_by_params(experiment_name) || override_alternative_by_cookies(experiment_name)
end
def override_alternative(experiment_name)
override_alternative_by_params(experiment_name) || override_alternative_by_cookies(experiment_name)
end
def override_alternative_by_params(experiment_name)
defined?(params) && params[OVERRIDE_PARAM_NAME] && params[OVERRIDE_PARAM_NAME][experiment_name]
end
def override_alternative_by_cookies(experiment_name)
return unless defined?(request)
if request.cookies && request.cookies.key?("split_override")
experiments = JSON.parse(request.cookies["split_override"]) rescue {}
experiments[experiment_name]
end
end
def split_generically_disabled?
defined?(params) && params["SPLIT_DISABLE"]
end
def ab_user
@ab_user ||= User.new(self)
end
def exclude_visitor?
defined?(request) && (instance_exec(request, &Split.configuration.ignore_filter) || is_ignored_ip_address? || is_robot? || is_preview?)
end
def is_robot?
defined?(request) && request.user_agent =~ Split.configuration.robot_regex
end
def is_preview?
defined?(request) && defined?(request.headers) && request.headers["x-purpose"] == "preview"
end
def is_ignored_ip_address?
return false if Split.configuration.ignore_ip_addresses.empty?
Split.configuration.ignore_ip_addresses.each do |ip|
return true if defined?(request) && (request.ip == ip || (ip.class == Regexp && request.ip =~ ip))
end
false
end
def active_experiments
ab_user.active_experiments
end
def normalize_metric(metric_descriptor)
if Hash === metric_descriptor
experiment_name = metric_descriptor.keys.first
goals = Array(metric_descriptor.values.first)
else
experiment_name = metric_descriptor
goals = []
end
return experiment_name, goals
end
def control_variable(control)
Hash === control ? control.keys.first.to_s : control.to_s
end
end
end
<MSG> Merge pull request #310 from fusion2004/handle-dns-resolving-errors
If the DNS resolution fails for your redis server, ruby will throw a SocketError, which is currently not rescued by the ab_test helper
<DFF> @@ -16,7 +16,7 @@ module Split
else
control_variable(experiment.control)
end
- rescue Errno::ECONNREFUSED, Redis::CannotConnectError => e
+ rescue Errno::ECONNREFUSED, Redis::CannotConnectError, SocketError => e
raise(e) unless Split.configuration.db_failover
Split.configuration.db_failover_on_db_error.call(e)
| 1 | Merge pull request #310 from fusion2004/handle-dns-resolving-errors | 1 | .rb | rb | mit | splitrb/split |
10071870 | <NME> README.md
<BEF> # [Split](https://libraries.io/rubygems/split)
[](http://badge.fury.io/rb/split)

[](https://codeclimate.com/github/splitrb/split)
[](https://codeclimate.com/github/splitrb/split/coverage)
[](https://github.com/RichardLitt/standard-readme)
[](https://www.codetriage.com/splitrb/split)
> 📈 The Rack Based A/B testing framework https://libraries.io/rubygems/split
Split is a rack based A/B testing framework designed to work with Rails, Sinatra or any other rack based app.
Split is heavily inspired by the [Abingo](https://github.com/ryanb/abingo) and [Vanity](https://github.com/assaf/vanity) Rails A/B testing plugins and [Resque](https://github.com/resque/resque) in its use of Redis.
Split is designed to be hacker friendly, allowing for maximum customisation and extensibility.
## Install
### Requirements
Split v4.0+ is currently tested with Ruby >= 2.5 and Rails >= 5.2.
If your project requires compatibility with Ruby 2.4.x or older Rails versions. You can try v3.0 or v0.8.0(for Ruby 1.9.3)
Split uses Redis as a datastore.
Split only supports Redis 4.0 or greater.
If you're on OS X, Homebrew is the simplest way to install Redis:
```bash
brew install redis
redis-server /usr/local/etc/redis.conf
```
You now have a Redis daemon running on port `6379`.
### Setup
```bash
gem install split
```
#### Rails
Adding `gem 'split'` to your Gemfile will autoload it when rails starts up, as long as you've configured Redis it will 'just work'.
#### Sinatra
To configure Sinatra with Split you need to enable sessions and mix in the helper methods. Add the following lines at the top of your Sinatra app:
```ruby
require 'split'
class MySinatraApp < Sinatra::Base
enable :sessions
helpers Split::Helper
get '/' do
...
end
```
## Usage
To begin your A/B test use the `ab_test` method, naming your experiment with the first argument and then the different alternatives which you wish to test on as the other arguments.
`ab_test` returns one of the alternatives, if a user has already seen that test they will get the same alternative as before, which you can use to split your code on.
It can be used to render different templates, show different text or any other case based logic.
`ab_finished` is used to make a completion of an experiment, or conversion.
Example: View
```erb
<% ab_test(:login_button, "/images/button1.jpg", "/images/button2.jpg") do |button_file| %>
<%= image_tag(button_file, alt: "Login!") %>
<% end %>
```
Example: Controller
```ruby
def register_new_user
```erb
<% ab_test("login_button", "/images/button1.jpg", "/images/button2.jpg") do |button_file| %>
<%= img_tag(button_file, :alt => "Login!") %>
<% end %>
```
```ruby
def buy_new_points
# some business logic
ab_finished(:new_user_free_points)
end
```
Example: Conversion tracking (in a view)
```erb
Thanks for signing up, dude! <% ab_finished(:signup_page_redesign) %>
```
You can find more examples, tutorials and guides on the [wiki](https://github.com/splitrb/split/wiki).
## Statistical Validity
Split has two options for you to use to determine which alternative is the best.
The first option (default on the dashboard) uses a z test (n>30) for the difference between your control and alternative conversion rates to calculate statistical significance. This test will tell you whether an alternative is better or worse than your control, but it will not distinguish between which alternative is the best in an experiment with multiple alternatives. Split will only tell you if your experiment is 90%, 95%, or 99% significant, and this test only works if you have more than 30 participants and 5 conversions for each branch.
As per this [blog post](https://www.evanmiller.org/how-not-to-run-an-ab-test.html) on the pitfalls of A/B testing, it is highly recommended that you determine your requisite sample size for each branch before running the experiment. Otherwise, you'll have an increased rate of false positives (experiments which show a significant effect where really there is none).
[Here](https://www.evanmiller.org/ab-testing/sample-size.html) is a sample size calculator for your convenience.
The second option uses simulations from a beta distribution to determine the probability that the given alternative is the winner compared to all other alternatives. You can view these probabilities by clicking on the drop-down menu labeled "Confidence." This option should be used when the experiment has more than just 1 control and 1 alternative. It can also be used for a simple, 2-alternative A/B test.
Calculating the beta-distribution simulations for a large number of experiments can be slow, so the results are cached. You can specify how often they should be recalculated (the default is once per day).
```ruby
Split.configure do |config|
config.winning_alternative_recalculation_interval = 3600 # 1 hour
end
```
## Extras
### Weighted alternatives
Perhaps you only want to show an alternative to 10% of your visitors because it is very experimental or not yet fully load tested.
To do this you can pass a weight with each alternative in the following ways:
```ruby
ab_test(:homepage_design, {'Old' => 18}, {'New' => 2})
ab_test(:homepage_design, 'Old', {'New' => 1.0/9})
ab_test(:homepage_design, {'Old' => 9}, 'New')
```
This will only show the new alternative to visitors 1 in 10 times, the default weight for an alternative is 1.
### Overriding alternatives
For development and testing, you may wish to force your app to always return an alternative.
You can do this by passing it as a parameter in the url.
If you have an experiment called `button_color` with alternatives called `red` and `blue` used on your homepage, a url such as:
http://myawesomesite.com?ab_test[button_color]=red
will always have red buttons. This won't be stored in your session or count towards to results, unless you set the `store_override` configuration option.
In the event you want to disable all tests without having to know the individual experiment names, add a `SPLIT_DISABLE` query parameter.
http://myawesomesite.com?SPLIT_DISABLE=true
It is not required to send `SPLIT_DISABLE=false` to activate Split.
### Rspec Helper
To aid testing with RSpec, write `spec/support/split_helper.rb` and call `use_ab_test(alternatives_by_experiment)` in your specs as instructed below:
```ruby
# Create a file with these contents at 'spec/support/split_helper.rb'
# and ensure it is `require`d in your rails_helper.rb or spec_helper.rb
module SplitHelper
# Force a specific experiment alternative to always be returned:
# use_ab_test(signup_form: "single_page")
#
# Force alternatives for multiple experiments:
# use_ab_test(signup_form: "single_page", pricing: "show_enterprise_prices")
#
def use_ab_test(alternatives_by_experiment)
allow_any_instance_of(Split::Helper).to receive(:ab_test) do |_receiver, experiment, &block|
variant = alternatives_by_experiment.fetch(experiment) { |key| raise "Unknown experiment '#{key}'" }
block.call(variant) unless block.nil?
variant
end
end
end
# Make the `use_ab_test` method available to all specs:
RSpec.configure do |config|
config.include SplitHelper
end
```
Now you can call `use_ab_test(alternatives_by_experiment)` in your specs, for example:
```ruby
it "registers using experimental signup" do
use_ab_test experiment_name: "alternative_name"
post "/signups"
...
end
```
### Starting experiments manually
By default new A/B tests will be active right after deployment. In case you would like to start new test a while after
the deploy, you can do it by setting the `start_manually` configuration option to `true`.
After choosing this option tests won't be started right after deploy, but after pressing the `Start` button in Split admin dashboard. If a test is deleted from the Split dashboard, then it can only be started after pressing the `Start` button whenever being re-initialized.
### Reset after completion
When a user completes a test their session is reset so that they may start the test again in the future.
To stop this behaviour you can pass the following option to the `ab_finished` method:
```ruby
ab_finished(:experiment_name, reset: false)
```
The user will then always see the alternative they started with.
Any old unfinished experiment key will be deleted from the user's data storage if the experiment had been removed or is over and a winner had been chosen. This allows a user to enroll into any new experiment in cases when the `allow_multiple_experiments` config option is set to `false`.
### Reset experiments manually
By default Split automatically resets the experiment whenever it detects the configuration for an experiment has changed (e.g. you call `ab_test` with different alternatives). You can prevent this by setting the option `reset_manually` to `true`.
You may want to do this when you want to change something, like the variants' names, the metadata about an experiment, etc. without resetting everything.
### Multiple experiments at once
By default Split will avoid users participating in multiple experiments at once. This means you are less likely to skew results by adding in more variation to your tests.
To stop this behaviour and allow users to participate in multiple experiments at once set the `allow_multiple_experiments` config option to true like so:
```ruby
Split.configure do |config|
config.allow_multiple_experiments = true
end
```
This will allow the user to participate in any number of experiments and belong to any alternative in each experiment. This has the possible downside of a variation in one experiment influencing the outcome of another.
To address this, setting the `allow_multiple_experiments` config option to 'control' like so:
```ruby
Split.configure do |config|
config.allow_multiple_experiments = 'control'
end
```
For this to work, each and every experiment you define must have an alternative named 'control'. This will allow the user to participate in multiple experiments as long as the user belongs to the alternative 'control' in each experiment. As soon as the user belongs to an alternative named something other than 'control' the user may not participate in any more experiments. Calling ab_test(<other experiments>) will always return the first alternative without adding the user to that experiment.
### Experiment Persistence
Split comes with three built-in persistence adapters for storing users and the alternatives they've been given for each experiment.
By default Split will store the tests for each user in the session.
You can optionally configure Split to use a cookie, Redis, or any custom adapter of your choosing.
#### Cookies
```ruby
Split.configure do |config|
config.persistence = :cookie
end
```
When using the cookie persistence, Split stores data into an anonymous tracking cookie named 'split', which expires in 1 year. To change that, set the `persistence_cookie_length` in the configuration (unit of time in seconds).
```ruby
Split.configure do |config|
config.persistence = :cookie
config.persistence_cookie_length = 2592000 # 30 days
end
```
The data stored consists of the experiment name and the variants the user is in. Example: { "experiment_name" => "variant_a" }
__Note:__ Using cookies depends on `ActionDispatch::Cookies` or any identical API
#### Redis
Using Redis will allow ab_users to persist across sessions or machines.
```ruby
Split.configure do |config|
config.persistence = Split::Persistence::RedisAdapter.with_config(lookup_by: -> (context) { context.current_user_id })
# Equivalent
# config.persistence = Split::Persistence::RedisAdapter.with_config(lookup_by: :current_user_id)
end
```
Options:
* `lookup_by`: method to invoke per request for uniquely identifying ab_users (mandatory configuration)
* `namespace`: separate namespace to store these persisted values (default "persistence")
* `expire_seconds`: sets TTL for user key. (if a user is in multiple experiments most recent update will reset TTL for all their assignments)
#### Dual Adapter
The Dual Adapter allows the use of different persistence adapters for logged-in and logged-out users. A common use case is to use Redis for logged-in users and Cookies for logged-out users.
```ruby
cookie_adapter = Split::Persistence::CookieAdapter
redis_adapter = Split::Persistence::RedisAdapter.with_config(
lookup_by: -> (context) { context.send(:current_user).try(:id) },
expire_seconds: 2592000)
Split.configure do |config|
config.persistence = Split::Persistence::DualAdapter.with_config(
logged_in: -> (context) { !context.send(:current_user).try(:id).nil? },
logged_in_adapter: redis_adapter,
logged_out_adapter: cookie_adapter)
config.persistence_cookie_length = 2592000 # 30 days
end
```
#### Custom Adapter
Your custom adapter needs to implement the same API as existing adapters.
See `Split::Persistence::CookieAdapter` or `Split::Persistence::SessionAdapter` for a starting point.
```ruby
Split.configure do |config|
config.persistence = YourCustomAdapterClass
end
```
### Trial Event Hooks
You can define methods that will be called at the same time as experiment
alternative participation and goal completion.
For example:
``` ruby
Split.configure do |config|
config.on_trial = :log_trial # run on every trial
config.on_trial_choose = :log_trial_choose # run on trials with new users only
config.on_trial_complete = :log_trial_complete
end
```
Set these attributes to a method name available in the same context as the
`ab_test` method. These methods should accept one argument, a `Trial` instance.
``` ruby
def log_trial(trial)
logger.info "experiment=%s alternative=%s user=%s" %
[ trial.experiment.name, trial.alternative, current_user.id ]
end
def log_trial_choose(trial)
logger.info "[new user] experiment=%s alternative=%s user=%s" %
[ trial.experiment.name, trial.alternative, current_user.id ]
end
def log_trial_complete(trial)
logger.info "experiment=%s alternative=%s user=%s complete=true" %
[ trial.experiment.name, trial.alternative, current_user.id ]
end
```
#### Views
If you are running `ab_test` from a view, you must define your event
hook callback as a
[helper_method](https://apidock.com/rails/AbstractController/Helpers/ClassMethods/helper_method)
in the controller:
``` ruby
helper_method :log_trial_choose
def log_trial_choose(trial)
logger.info "experiment=%s alternative=%s user=%s" %
[ trial.experiment.name, trial.alternative, current_user.id ]
end
```
### Experiment Hooks
You can assign a proc that will be called when an experiment is reset or deleted. You can use these hooks to call methods within your application to keep data related to experiments in sync with Split.
For example:
``` ruby
Split.configure do |config|
# after experiment reset or deleted
config.on_experiment_reset = -> (example) { # Do something on reset }
config.on_experiment_delete = -> (experiment) { # Do something else on delete }
# before experiment reset or deleted
config.on_before_experiment_reset = -> (example) { # Do something on reset }
config.on_before_experiment_delete = -> (experiment) { # Do something else on delete }
# after experiment winner had been set
config.on_experiment_winner_choose = -> (experiment) { # Do something on winner choose }
end
```
## Web Interface
Split comes with a Sinatra-based front end to get an overview of how your experiments are doing.
If you are running Rails 2: You can mount this inside your app using Rack::URLMap in your `config.ru`
```ruby
require 'split/dashboard'
run Rack::URLMap.new \
"/" => Your::App.new,
"/split" => Split::Dashboard.new
```
However, if you are using Rails 3 or higher: You can mount this inside your app routes by first adding this to the Gemfile:
```ruby
gem 'split', require: 'split/dashboard'
```
Then adding this to config/routes.rb
```ruby
mount Split::Dashboard, at: 'split'
```
You may want to password protect that page, you can do so with `Rack::Auth::Basic` (in your split initializer file)
```ruby
# Rails apps or apps that already depend on activesupport
Split::Dashboard.use Rack::Auth::Basic do |username, password|
# Protect against timing attacks:
# - Use & (do not use &&) so that it doesn't short circuit.
# - Use digests to stop length information leaking
ActiveSupport::SecurityUtils.secure_compare(::Digest::SHA256.hexdigest(username), ::Digest::SHA256.hexdigest(ENV["SPLIT_USERNAME"])) &
ActiveSupport::SecurityUtils.secure_compare(::Digest::SHA256.hexdigest(password), ::Digest::SHA256.hexdigest(ENV["SPLIT_PASSWORD"]))
end
# Apps without activesupport
Split::Dashboard.use Rack::Auth::Basic do |username, password|
# Protect against timing attacks:
# - Use & (do not use &&) so that it doesn't short circuit.
# - Use digests to stop length information leaking
Rack::Utils.secure_compare(::Digest::SHA256.hexdigest(username), ::Digest::SHA256.hexdigest(ENV["SPLIT_USERNAME"])) &
Rack::Utils.secure_compare(::Digest::SHA256.hexdigest(password), ::Digest::SHA256.hexdigest(ENV["SPLIT_PASSWORD"]))
end
```
You can even use Devise or any other Warden-based authentication method to authorize users. Just replace `mount Split::Dashboard, :at => 'split'` in `config/routes.rb` with the following:
```ruby
match "/split" => Split::Dashboard, anchor: false, via: [:get, :post, :delete], constraints: -> (request) do
request.env['warden'].authenticated? # are we authenticated?
request.env['warden'].authenticate! # authenticate if not already
# or even check any other condition such as request.env['warden'].user.is_admin?
end
```
More information on this [here](https://steve.dynedge.co.uk/2011/12/09/controlling-access-to-routes-and-rack-apps-in-rails-3-with-devise-and-warden/)
### Screenshot

## Configuration
You can override the default configuration options of Split like so:
```ruby
Split.configure do |config|
config.db_failover = true # handle Redis errors gracefully
config.db_failover_on_db_error = -> (error) { Rails.logger.error(error.message) }
config.allow_multiple_experiments = true
config.enabled = true
config.persistence = Split::Persistence::SessionAdapter
#config.start_manually = false ## new test will have to be started manually from the admin panel. default false
#config.reset_manually = false ## if true, it never resets the experiment data, even if the configuration changes
config.include_rails_helper = true
config.redis = "redis://custom.redis.url:6380"
end
```
Split looks for the Redis host in the environment variable `REDIS_URL` then
defaults to `redis://localhost:6379` if not specified by configure block.
On platforms like Heroku, Split will use the value of `REDIS_PROVIDER` to
determine which env variable key to use when retrieving the host config. This
defaults to `REDIS_URL`.
### Filtering
In most scenarios you don't want to have AB-Testing enabled for web spiders, robots or special groups of users.
Split provides functionality to filter this based on a predefined, extensible list of bots, IP-lists or custom exclude logic.
```ruby
Split.configure do |config|
# bot config
config.robot_regex = /my_custom_robot_regex/ # or
config.bots['newbot'] = "Description for bot with 'newbot' user agent, which will be added to config.robot_regex for exclusion"
# IP config
config.ignore_ip_addresses << '81.19.48.130' # or regex: /81\.19\.48\.[0-9]+/
# or provide your own filter functionality, the default is proc{ |request| is_robot? || is_ignored_ip_address? || is_preview? }
config.ignore_filter = -> (request) { CustomExcludeLogic.excludes?(request) }
end
```
### Experiment configuration
Instead of providing the experiment options inline, you can store them
in a hash. This hash can control your experiment's alternatives, weights,
algorithm and if the experiment resets once finished:
```ruby
Split.configure do |config|
config.experiments = {
my_first_experiment: {
alternatives: ["a", "b"],
resettable: false
},
:my_second_experiment => {
algorithm: 'Split::Algorithms::Whiplash',
alternatives: [
{ name: "a", percent: 67 },
{ name: "b", percent: 33 }
]
}
}
end
```
You can also store your experiments in a YAML file:
```ruby
Split.configure do |config|
config.experiments = YAML.load_file "config/experiments.yml"
end
```
You can then define the YAML file like:
```yaml
my_first_experiment:
alternatives:
- a
- b
my_second_experiment:
alternatives:
- name: a
percent: 67
- name: b
percent: 33
resettable: false
```
This simplifies the calls from your code:
```ruby
ab_test(:my_first_experiment)
```
and:
```ruby
ab_finished(:my_first_experiment)
```
You can also add meta data for each experiment, which is very useful when you need more than an alternative name to change behaviour:
```ruby
Split.configure do |config|
config.experiments = {
my_first_experiment: {
alternatives: ["a", "b"],
metadata: {
"a" => {"text" => "Have a fantastic day"},
"b" => {"text" => "Don't get hit by a bus"}
}
}
}
end
```
```yaml
my_first_experiment:
alternatives:
- a
- b
metadata:
a:
text: "Have a fantastic day"
b:
text: "Don't get hit by a bus"
```
This allows for some advanced experiment configuration using methods like:
```ruby
trial.alternative.name # => "a"
trial.metadata['text'] # => "Have a fantastic day"
```
or in views:
```erb
<% ab_test("my_first_experiment") do |alternative, meta| %>
<%= alternative %>
<small><%= meta['text'] %></small>
<% end %>
```
The keys used in meta data should be Strings
#### Metrics
You might wish to track generic metrics, such as conversions, and use
those to complete multiple different experiments without adding more to
your code. You can use the configuration hash to do this, thanks to
the `:metric` option.
```ruby
Split.configure do |config|
config.experiments = {
my_first_experiment: {
alternatives: ["a", "b"],
metric: :my_metric
}
}
end
```
Your code may then track a completion using the metric instead of
the experiment name:
```ruby
ab_finished(:my_metric)
```
You can also create a new metric by instantiating and saving a new Metric object.
```ruby
Split::Metric.new(:my_metric)
Split::Metric.save
```
#### Goals
You might wish to allow an experiment to have multiple, distinguishable goals.
The API to define goals for an experiment is this:
```ruby
ab_test({link_color: ["purchase", "refund"]}, "red", "blue")
```
or you can define them in a configuration file:
```ruby
Split.configure do |config|
config.experiments = {
link_color: {
alternatives: ["red", "blue"],
goals: ["purchase", "refund"]
}
}
end
```
To complete a goal conversion, you do it like:
```ruby
ab_finished(link_color: "purchase")
```
Note that if you pass additional options, that should be a separate hash:
```ruby
ab_finished({ link_color: "purchase" }, reset: false)
```
**NOTE:** This does not mean that a single experiment can complete more than one goal.
Once you finish one of the goals, the test is considered to be completed, and finishing the other goal will no longer register. (Assuming the test runs with `reset: false`.)
**Good Example**: Test if listing Plan A first result in more conversions to Plan A (goal: "plana_conversion") or Plan B (goal: "planb_conversion").
**Bad Example**: Test if button color increases conversion rate through multiple steps of a funnel. THIS WILL NOT WORK.
**Bad Example**: Test both how button color affects signup *and* how it affects login, at the same time. THIS WILL NOT WORK.
#### Combined Experiments
If you want to test how button color affects signup *and* how it affects login at the same time, use combined experiments.
Configure like so:
```ruby
Split.configuration.experiments = {
:button_color_experiment => {
:alternatives => ["blue", "green"],
:combined_experiments => ["button_color_on_signup", "button_color_on_login"]
}
}
```
Starting the combined test starts all combined experiments
```ruby
ab_combined_test(:button_color_experiment)
```
Finish each combined test as normal
```ruby
ab_finished(:button_color_on_login)
ab_finished(:button_color_on_signup)
```
**Additional Configuration**:
* Be sure to enable `allow_multiple_experiments`
* In Sinatra include the CombinedExperimentsHelper
```
helpers Split::CombinedExperimentsHelper
```
### DB failover solution
Due to the fact that Redis has no automatic failover mechanism, it's
possible to switch on the `db_failover` config option, so that `ab_test`
and `ab_finished` will not crash in case of a db failure. `ab_test` always
delivers alternative A (the first one) in that case.
It's also possible to set a `db_failover_on_db_error` callback (proc)
for example to log these errors via Rails.logger.
### Redis
You may want to change the Redis host and port Split connects to, or
set various other options at startup.
Split has a `redis` setter which can be given a string or a Redis
object. This means if you're already using Redis in your app, Split
can re-use the existing connection.
String: `Split.redis = 'redis://localhost:6379'`
Redis: `Split.redis = $redis`
For our rails app we have a `config/initializers/split.rb` file where
we load `config/split.yml` by hand and set the Redis information
appropriately.
Here's our `config/split.yml`:
```yml
development: redis://localhost:6379
test: redis://localhost:6379
staging: redis://redis1.example.com:6379
fi: redis://localhost:6379
production: redis://redis1.example.com:6379
```
And our initializer:
```ruby
split_config = YAML.load_file(Rails.root.join('config', 'split.yml'))
Split.redis = split_config[Rails.env]
```
### Redis Caching (v4.0+)
In some high-volume usage scenarios, Redis load can be incurred by repeated
fetches for fairly static data. Enabling caching will reduce this load.
```ruby
Split.configuration.cache = true
````
This currently caches:
- `Split::ExperimentCatalog.find`
- `Split::Experiment.start_time`
- `Split::Experiment.winner`
## Namespaces
If you're running multiple, separate instances of Split you may want
to namespace the keyspaces so they do not overlap. This is not unlike
the approach taken by many memcached clients.
This feature can be provided by the [redis-namespace](https://github.com/defunkt/redis-namespace)
library. To configure Split to use `Redis::Namespace`, do the following:
1. Add `redis-namespace` to your Gemfile:
```ruby
gem 'redis-namespace'
```
2. Configure `Split.redis` to use a `Redis::Namespace` instance (possible in an
initializer):
```ruby
redis = Redis.new(url: ENV['REDIS_URL']) # or whatever config you want
Split.redis = Redis::Namespace.new(:your_namespace, redis: redis)
```
## Outside of a Web Session
Split provides the Helper module to facilitate running experiments inside web sessions.
Alternatively, you can access the underlying Metric, Trial, Experiment and Alternative objects to
conduct experiments that are not tied to a web session.
```ruby
# create a new experiment
experiment = Split::ExperimentCatalog.find_or_create('color', 'red', 'blue')
# create a new trial
trial = Split::Trial.new(:experiment => experiment)
# run trial
trial.choose!
# get the result, returns either red or blue
trial.alternative.name
# if the goal has been achieved, increment the successful completions for this alternative.
if goal_achieved?
trial.complete!
end
```
## Algorithms
By default, Split ships with `Split::Algorithms::WeightedSample` that randomly selects from possible alternatives for a traditional a/b test.
It is possible to specify static weights to favor certain alternatives.
`Split::Algorithms::Whiplash` is an implementation of a [multi-armed bandit algorithm](http://stevehanov.ca/blog/index.php?id=132).
This algorithm will automatically weight the alternatives based on their relative performance,
choosing the better-performing ones more often as trials are completed.
`Split::Algorithms::BlockRandomization` is an algorithm that ensures equal
participation across all alternatives. This algorithm will choose the alternative
with the fewest participants. In the event of multiple minimum participant alternatives
(i.e. starting a new "Block") the algorithm will choose a random alternative from
those minimum participant alternatives.
Users may also write their own algorithms. The default algorithm may be specified globally in the configuration file, or on a per experiment basis using the experiments hash of the configuration file.
To change the algorithm globally for all experiments, use the following in your initializer:
```ruby
Split.configure do |config|
config.algorithm = Split::Algorithms::Whiplash
end
```
## Extensions
- [Split::Export](https://github.com/splitrb/split-export) - Easily export A/B test data out of Split.
- [Split::Analytics](https://github.com/splitrb/split-analytics) - Push test data to Google Analytics.
- [Split::Mongoid](https://github.com/MongoHQ/split-mongoid) - Store experiment data in mongoid (still uses redis).
- [Split::Cacheable](https://github.com/harrystech/split_cacheable) - Automatically create cache buckets per test.
- [Split::Counters](https://github.com/bernardkroes/split-counters) - Add counters per experiment and alternative.
- [Split::Cli](https://github.com/craigmcnamara/split-cli) - A CLI to trigger Split A/B tests.
## Screencast
Ryan bates has produced an excellent 10 minute screencast about split on the Railscasts site: [A/B Testing with Split](http://railscasts.com/episodes/331-a-b-testing-with-split)
## Blogposts
* [Recipe: A/B testing with KISSMetrics and the split gem](https://robots.thoughtbot.com/post/9595887299/recipe-a-b-testing-with-kissmetrics-and-the-split-gem)
* [Rails A/B testing with Split on Heroku](http://blog.nathanhumbert.com/2012/02/rails-ab-testing-with-split-on-heroku.html)
## Backers
Support us with a monthly donation and help us continue our activities. [[Become a backer](https://opencollective.com/split#backer)]
<a href="https://opencollective.com/split/backer/0/website" target="_blank"><img src="https://opencollective.com/split/backer/0/avatar.svg"></a>
<a href="https://opencollective.com/split/backer/1/website" target="_blank"><img src="https://opencollective.com/split/backer/1/avatar.svg"></a>
<a href="https://opencollective.com/split/backer/2/website" target="_blank"><img src="https://opencollective.com/split/backer/2/avatar.svg"></a>
<a href="https://opencollective.com/split/backer/3/website" target="_blank"><img src="https://opencollective.com/split/backer/3/avatar.svg"></a>
<a href="https://opencollective.com/split/backer/4/website" target="_blank"><img src="https://opencollective.com/split/backer/4/avatar.svg"></a>
<a href="https://opencollective.com/split/backer/5/website" target="_blank"><img src="https://opencollective.com/split/backer/5/avatar.svg"></a>
<a href="https://opencollective.com/split/backer/6/website" target="_blank"><img src="https://opencollective.com/split/backer/6/avatar.svg"></a>
<a href="https://opencollective.com/split/backer/7/website" target="_blank"><img src="https://opencollective.com/split/backer/7/avatar.svg"></a>
<a href="https://opencollective.com/split/backer/8/website" target="_blank"><img src="https://opencollective.com/split/backer/8/avatar.svg"></a>
<a href="https://opencollective.com/split/backer/9/website" target="_blank"><img src="https://opencollective.com/split/backer/9/avatar.svg"></a>
<a href="https://opencollective.com/split/backer/10/website" target="_blank"><img src="https://opencollective.com/split/backer/10/avatar.svg"></a>
<a href="https://opencollective.com/split/backer/11/website" target="_blank"><img src="https://opencollective.com/split/backer/11/avatar.svg"></a>
<a href="https://opencollective.com/split/backer/12/website" target="_blank"><img src="https://opencollective.com/split/backer/12/avatar.svg"></a>
<a href="https://opencollective.com/split/backer/13/website" target="_blank"><img src="https://opencollective.com/split/backer/13/avatar.svg"></a>
<a href="https://opencollective.com/split/backer/14/website" target="_blank"><img src="https://opencollective.com/split/backer/14/avatar.svg"></a>
<a href="https://opencollective.com/split/backer/15/website" target="_blank"><img src="https://opencollective.com/split/backer/15/avatar.svg"></a>
<a href="https://opencollective.com/split/backer/16/website" target="_blank"><img src="https://opencollective.com/split/backer/16/avatar.svg"></a>
<a href="https://opencollective.com/split/backer/17/website" target="_blank"><img src="https://opencollective.com/split/backer/17/avatar.svg"></a>
<a href="https://opencollective.com/split/backer/18/website" target="_blank"><img src="https://opencollective.com/split/backer/18/avatar.svg"></a>
<a href="https://opencollective.com/split/backer/19/website" target="_blank"><img src="https://opencollective.com/split/backer/19/avatar.svg"></a>
<a href="https://opencollective.com/split/backer/20/website" target="_blank"><img src="https://opencollective.com/split/backer/20/avatar.svg"></a>
<a href="https://opencollective.com/split/backer/21/website" target="_blank"><img src="https://opencollective.com/split/backer/21/avatar.svg"></a>
<a href="https://opencollective.com/split/backer/22/website" target="_blank"><img src="https://opencollective.com/split/backer/22/avatar.svg"></a>
<a href="https://opencollective.com/split/backer/23/website" target="_blank"><img src="https://opencollective.com/split/backer/23/avatar.svg"></a>
<a href="https://opencollective.com/split/backer/24/website" target="_blank"><img src="https://opencollective.com/split/backer/24/avatar.svg"></a>
<a href="https://opencollective.com/split/backer/25/website" target="_blank"><img src="https://opencollective.com/split/backer/25/avatar.svg"></a>
<a href="https://opencollective.com/split/backer/26/website" target="_blank"><img src="https://opencollective.com/split/backer/26/avatar.svg"></a>
<a href="https://opencollective.com/split/backer/27/website" target="_blank"><img src="https://opencollective.com/split/backer/27/avatar.svg"></a>
<a href="https://opencollective.com/split/backer/28/website" target="_blank"><img src="https://opencollective.com/split/backer/28/avatar.svg"></a>
<a href="https://opencollective.com/split/backer/29/website" target="_blank"><img src="https://opencollective.com/split/backer/29/avatar.svg"></a>
## 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/split#sponsor)]
<a href="https://opencollective.com/split/sponsor/0/website" target="_blank"><img src="https://opencollective.com/split/sponsor/0/avatar.svg"></a>
<a href="https://opencollective.com/split/sponsor/1/website" target="_blank"><img src="https://opencollective.com/split/sponsor/1/avatar.svg"></a>
<a href="https://opencollective.com/split/sponsor/2/website" target="_blank"><img src="https://opencollective.com/split/sponsor/2/avatar.svg"></a>
<a href="https://opencollective.com/split/sponsor/3/website" target="_blank"><img src="https://opencollective.com/split/sponsor/3/avatar.svg"></a>
<a href="https://opencollective.com/split/sponsor/4/website" target="_blank"><img src="https://opencollective.com/split/sponsor/4/avatar.svg"></a>
<a href="https://opencollective.com/split/sponsor/5/website" target="_blank"><img src="https://opencollective.com/split/sponsor/5/avatar.svg"></a>
<a href="https://opencollective.com/split/sponsor/6/website" target="_blank"><img src="https://opencollective.com/split/sponsor/6/avatar.svg"></a>
<a href="https://opencollective.com/split/sponsor/7/website" target="_blank"><img src="https://opencollective.com/split/sponsor/7/avatar.svg"></a>
<a href="https://opencollective.com/split/sponsor/8/website" target="_blank"><img src="https://opencollective.com/split/sponsor/8/avatar.svg"></a>
<a href="https://opencollective.com/split/sponsor/9/website" target="_blank"><img src="https://opencollective.com/split/sponsor/9/avatar.svg"></a>
<a href="https://opencollective.com/split/sponsor/10/website" target="_blank"><img src="https://opencollective.com/split/sponsor/10/avatar.svg"></a>
<a href="https://opencollective.com/split/sponsor/11/website" target="_blank"><img src="https://opencollective.com/split/sponsor/11/avatar.svg"></a>
<a href="https://opencollective.com/split/sponsor/12/website" target="_blank"><img src="https://opencollective.com/split/sponsor/12/avatar.svg"></a>
<a href="https://opencollective.com/split/sponsor/13/website" target="_blank"><img src="https://opencollective.com/split/sponsor/13/avatar.svg"></a>
<a href="https://opencollective.com/split/sponsor/14/website" target="_blank"><img src="https://opencollective.com/split/sponsor/14/avatar.svg"></a>
<a href="https://opencollective.com/split/sponsor/15/website" target="_blank"><img src="https://opencollective.com/split/sponsor/15/avatar.svg"></a>
<a href="https://opencollective.com/split/sponsor/16/website" target="_blank"><img src="https://opencollective.com/split/sponsor/16/avatar.svg"></a>
<a href="https://opencollective.com/split/sponsor/17/website" target="_blank"><img src="https://opencollective.com/split/sponsor/17/avatar.svg"></a>
<a href="https://opencollective.com/split/sponsor/18/website" target="_blank"><img src="https://opencollective.com/split/sponsor/18/avatar.svg"></a>
<a href="https://opencollective.com/split/sponsor/19/website" target="_blank"><img src="https://opencollective.com/split/sponsor/19/avatar.svg"></a>
<a href="https://opencollective.com/split/sponsor/20/website" target="_blank"><img src="https://opencollective.com/split/sponsor/20/avatar.svg"></a>
<a href="https://opencollective.com/split/sponsor/21/website" target="_blank"><img src="https://opencollective.com/split/sponsor/21/avatar.svg"></a>
<a href="https://opencollective.com/split/sponsor/22/website" target="_blank"><img src="https://opencollective.com/split/sponsor/22/avatar.svg"></a>
<a href="https://opencollective.com/split/sponsor/23/website" target="_blank"><img src="https://opencollective.com/split/sponsor/23/avatar.svg"></a>
<a href="https://opencollective.com/split/sponsor/24/website" target="_blank"><img src="https://opencollective.com/split/sponsor/24/avatar.svg"></a>
<a href="https://opencollective.com/split/sponsor/25/website" target="_blank"><img src="https://opencollective.com/split/sponsor/25/avatar.svg"></a>
<a href="https://opencollective.com/split/sponsor/26/website" target="_blank"><img src="https://opencollective.com/split/sponsor/26/avatar.svg"></a>
<a href="https://opencollective.com/split/sponsor/27/website" target="_blank"><img src="https://opencollective.com/split/sponsor/27/avatar.svg"></a>
<a href="https://opencollective.com/split/sponsor/28/website" target="_blank"><img src="https://opencollective.com/split/sponsor/28/avatar.svg"></a>
<a href="https://opencollective.com/split/sponsor/29/website" target="_blank"><img src="https://opencollective.com/split/sponsor/29/avatar.svg"></a>
## Contribute
Please do! Over 70 different people have contributed to the project, you can see them all here: https://github.com/splitrb/split/graphs/contributors.
### Development
The source code is hosted at [GitHub](https://github.com/splitrb/split).
Report issues and feature requests on [GitHub Issues](https://github.com/splitrb/split/issues).
You can find a discussion form on [Google Groups](https://groups.google.com/d/forum/split-ruby).
### Tests
Run the tests like this:
# Start a Redis server in another tab.
redis-server
bundle
rake spec
### A Note on Patches and Pull Requests
* Fork the project.
* Make your feature addition or bug fix.
* Add tests for it. This is important so I don't break it in a
future version unintentionally.
* Add documentation if necessary.
* Commit. Do not mess with the rakefile, version, or history.
(If you want to have your own version, that is fine. But bump the version in a commit by itself, which I can ignore when I pull.)
* Send a pull request. Bonus points for topic branches.
### Code of Conduct
Please note that this project is released with a [Contributor Code of Conduct](CODE_OF_CONDUCT.md). By participating in this project you agree to abide by its terms.
## Copyright
[MIT License](LICENSE) © 2019 [Andrew Nesbitt](https://github.com/andrew).
<MSG> Merge pull request #308 from jordelver/fix-image-helper-name
Fix image tag helper name
<DFF> @@ -87,7 +87,7 @@ Example: View
```erb
<% ab_test("login_button", "/images/button1.jpg", "/images/button2.jpg") do |button_file| %>
- <%= img_tag(button_file, :alt => "Login!") %>
+ <%= image_tag(button_file, :alt => "Login!") %>
<% end %>
```
| 1 | Merge pull request #308 from jordelver/fix-image-helper-name | 1 | .md | md | mit | splitrb/split |
10071871 | <NME> README.md
<BEF> # [Split](https://libraries.io/rubygems/split)
[](http://badge.fury.io/rb/split)

[](https://codeclimate.com/github/splitrb/split)
[](https://codeclimate.com/github/splitrb/split/coverage)
[](https://github.com/RichardLitt/standard-readme)
[](https://www.codetriage.com/splitrb/split)
> 📈 The Rack Based A/B testing framework https://libraries.io/rubygems/split
Split is a rack based A/B testing framework designed to work with Rails, Sinatra or any other rack based app.
Split is heavily inspired by the [Abingo](https://github.com/ryanb/abingo) and [Vanity](https://github.com/assaf/vanity) Rails A/B testing plugins and [Resque](https://github.com/resque/resque) in its use of Redis.
Split is designed to be hacker friendly, allowing for maximum customisation and extensibility.
## Install
### Requirements
Split v4.0+ is currently tested with Ruby >= 2.5 and Rails >= 5.2.
If your project requires compatibility with Ruby 2.4.x or older Rails versions. You can try v3.0 or v0.8.0(for Ruby 1.9.3)
Split uses Redis as a datastore.
Split only supports Redis 4.0 or greater.
If you're on OS X, Homebrew is the simplest way to install Redis:
```bash
brew install redis
redis-server /usr/local/etc/redis.conf
```
You now have a Redis daemon running on port `6379`.
### Setup
```bash
gem install split
```
#### Rails
Adding `gem 'split'` to your Gemfile will autoload it when rails starts up, as long as you've configured Redis it will 'just work'.
#### Sinatra
To configure Sinatra with Split you need to enable sessions and mix in the helper methods. Add the following lines at the top of your Sinatra app:
```ruby
require 'split'
class MySinatraApp < Sinatra::Base
enable :sessions
helpers Split::Helper
get '/' do
...
end
```
## Usage
To begin your A/B test use the `ab_test` method, naming your experiment with the first argument and then the different alternatives which you wish to test on as the other arguments.
`ab_test` returns one of the alternatives, if a user has already seen that test they will get the same alternative as before, which you can use to split your code on.
It can be used to render different templates, show different text or any other case based logic.
`ab_finished` is used to make a completion of an experiment, or conversion.
Example: View
```erb
<% ab_test(:login_button, "/images/button1.jpg", "/images/button2.jpg") do |button_file| %>
<%= image_tag(button_file, alt: "Login!") %>
<% end %>
```
Example: Controller
```ruby
def register_new_user
```erb
<% ab_test("login_button", "/images/button1.jpg", "/images/button2.jpg") do |button_file| %>
<%= img_tag(button_file, :alt => "Login!") %>
<% end %>
```
```ruby
def buy_new_points
# some business logic
ab_finished(:new_user_free_points)
end
```
Example: Conversion tracking (in a view)
```erb
Thanks for signing up, dude! <% ab_finished(:signup_page_redesign) %>
```
You can find more examples, tutorials and guides on the [wiki](https://github.com/splitrb/split/wiki).
## Statistical Validity
Split has two options for you to use to determine which alternative is the best.
The first option (default on the dashboard) uses a z test (n>30) for the difference between your control and alternative conversion rates to calculate statistical significance. This test will tell you whether an alternative is better or worse than your control, but it will not distinguish between which alternative is the best in an experiment with multiple alternatives. Split will only tell you if your experiment is 90%, 95%, or 99% significant, and this test only works if you have more than 30 participants and 5 conversions for each branch.
As per this [blog post](https://www.evanmiller.org/how-not-to-run-an-ab-test.html) on the pitfalls of A/B testing, it is highly recommended that you determine your requisite sample size for each branch before running the experiment. Otherwise, you'll have an increased rate of false positives (experiments which show a significant effect where really there is none).
[Here](https://www.evanmiller.org/ab-testing/sample-size.html) is a sample size calculator for your convenience.
The second option uses simulations from a beta distribution to determine the probability that the given alternative is the winner compared to all other alternatives. You can view these probabilities by clicking on the drop-down menu labeled "Confidence." This option should be used when the experiment has more than just 1 control and 1 alternative. It can also be used for a simple, 2-alternative A/B test.
Calculating the beta-distribution simulations for a large number of experiments can be slow, so the results are cached. You can specify how often they should be recalculated (the default is once per day).
```ruby
Split.configure do |config|
config.winning_alternative_recalculation_interval = 3600 # 1 hour
end
```
## Extras
### Weighted alternatives
Perhaps you only want to show an alternative to 10% of your visitors because it is very experimental or not yet fully load tested.
To do this you can pass a weight with each alternative in the following ways:
```ruby
ab_test(:homepage_design, {'Old' => 18}, {'New' => 2})
ab_test(:homepage_design, 'Old', {'New' => 1.0/9})
ab_test(:homepage_design, {'Old' => 9}, 'New')
```
This will only show the new alternative to visitors 1 in 10 times, the default weight for an alternative is 1.
### Overriding alternatives
For development and testing, you may wish to force your app to always return an alternative.
You can do this by passing it as a parameter in the url.
If you have an experiment called `button_color` with alternatives called `red` and `blue` used on your homepage, a url such as:
http://myawesomesite.com?ab_test[button_color]=red
will always have red buttons. This won't be stored in your session or count towards to results, unless you set the `store_override` configuration option.
In the event you want to disable all tests without having to know the individual experiment names, add a `SPLIT_DISABLE` query parameter.
http://myawesomesite.com?SPLIT_DISABLE=true
It is not required to send `SPLIT_DISABLE=false` to activate Split.
### Rspec Helper
To aid testing with RSpec, write `spec/support/split_helper.rb` and call `use_ab_test(alternatives_by_experiment)` in your specs as instructed below:
```ruby
# Create a file with these contents at 'spec/support/split_helper.rb'
# and ensure it is `require`d in your rails_helper.rb or spec_helper.rb
module SplitHelper
# Force a specific experiment alternative to always be returned:
# use_ab_test(signup_form: "single_page")
#
# Force alternatives for multiple experiments:
# use_ab_test(signup_form: "single_page", pricing: "show_enterprise_prices")
#
def use_ab_test(alternatives_by_experiment)
allow_any_instance_of(Split::Helper).to receive(:ab_test) do |_receiver, experiment, &block|
variant = alternatives_by_experiment.fetch(experiment) { |key| raise "Unknown experiment '#{key}'" }
block.call(variant) unless block.nil?
variant
end
end
end
# Make the `use_ab_test` method available to all specs:
RSpec.configure do |config|
config.include SplitHelper
end
```
Now you can call `use_ab_test(alternatives_by_experiment)` in your specs, for example:
```ruby
it "registers using experimental signup" do
use_ab_test experiment_name: "alternative_name"
post "/signups"
...
end
```
### Starting experiments manually
By default new A/B tests will be active right after deployment. In case you would like to start new test a while after
the deploy, you can do it by setting the `start_manually` configuration option to `true`.
After choosing this option tests won't be started right after deploy, but after pressing the `Start` button in Split admin dashboard. If a test is deleted from the Split dashboard, then it can only be started after pressing the `Start` button whenever being re-initialized.
### Reset after completion
When a user completes a test their session is reset so that they may start the test again in the future.
To stop this behaviour you can pass the following option to the `ab_finished` method:
```ruby
ab_finished(:experiment_name, reset: false)
```
The user will then always see the alternative they started with.
Any old unfinished experiment key will be deleted from the user's data storage if the experiment had been removed or is over and a winner had been chosen. This allows a user to enroll into any new experiment in cases when the `allow_multiple_experiments` config option is set to `false`.
### Reset experiments manually
By default Split automatically resets the experiment whenever it detects the configuration for an experiment has changed (e.g. you call `ab_test` with different alternatives). You can prevent this by setting the option `reset_manually` to `true`.
You may want to do this when you want to change something, like the variants' names, the metadata about an experiment, etc. without resetting everything.
### Multiple experiments at once
By default Split will avoid users participating in multiple experiments at once. This means you are less likely to skew results by adding in more variation to your tests.
To stop this behaviour and allow users to participate in multiple experiments at once set the `allow_multiple_experiments` config option to true like so:
```ruby
Split.configure do |config|
config.allow_multiple_experiments = true
end
```
This will allow the user to participate in any number of experiments and belong to any alternative in each experiment. This has the possible downside of a variation in one experiment influencing the outcome of another.
To address this, setting the `allow_multiple_experiments` config option to 'control' like so:
```ruby
Split.configure do |config|
config.allow_multiple_experiments = 'control'
end
```
For this to work, each and every experiment you define must have an alternative named 'control'. This will allow the user to participate in multiple experiments as long as the user belongs to the alternative 'control' in each experiment. As soon as the user belongs to an alternative named something other than 'control' the user may not participate in any more experiments. Calling ab_test(<other experiments>) will always return the first alternative without adding the user to that experiment.
### Experiment Persistence
Split comes with three built-in persistence adapters for storing users and the alternatives they've been given for each experiment.
By default Split will store the tests for each user in the session.
You can optionally configure Split to use a cookie, Redis, or any custom adapter of your choosing.
#### Cookies
```ruby
Split.configure do |config|
config.persistence = :cookie
end
```
When using the cookie persistence, Split stores data into an anonymous tracking cookie named 'split', which expires in 1 year. To change that, set the `persistence_cookie_length` in the configuration (unit of time in seconds).
```ruby
Split.configure do |config|
config.persistence = :cookie
config.persistence_cookie_length = 2592000 # 30 days
end
```
The data stored consists of the experiment name and the variants the user is in. Example: { "experiment_name" => "variant_a" }
__Note:__ Using cookies depends on `ActionDispatch::Cookies` or any identical API
#### Redis
Using Redis will allow ab_users to persist across sessions or machines.
```ruby
Split.configure do |config|
config.persistence = Split::Persistence::RedisAdapter.with_config(lookup_by: -> (context) { context.current_user_id })
# Equivalent
# config.persistence = Split::Persistence::RedisAdapter.with_config(lookup_by: :current_user_id)
end
```
Options:
* `lookup_by`: method to invoke per request for uniquely identifying ab_users (mandatory configuration)
* `namespace`: separate namespace to store these persisted values (default "persistence")
* `expire_seconds`: sets TTL for user key. (if a user is in multiple experiments most recent update will reset TTL for all their assignments)
#### Dual Adapter
The Dual Adapter allows the use of different persistence adapters for logged-in and logged-out users. A common use case is to use Redis for logged-in users and Cookies for logged-out users.
```ruby
cookie_adapter = Split::Persistence::CookieAdapter
redis_adapter = Split::Persistence::RedisAdapter.with_config(
lookup_by: -> (context) { context.send(:current_user).try(:id) },
expire_seconds: 2592000)
Split.configure do |config|
config.persistence = Split::Persistence::DualAdapter.with_config(
logged_in: -> (context) { !context.send(:current_user).try(:id).nil? },
logged_in_adapter: redis_adapter,
logged_out_adapter: cookie_adapter)
config.persistence_cookie_length = 2592000 # 30 days
end
```
#### Custom Adapter
Your custom adapter needs to implement the same API as existing adapters.
See `Split::Persistence::CookieAdapter` or `Split::Persistence::SessionAdapter` for a starting point.
```ruby
Split.configure do |config|
config.persistence = YourCustomAdapterClass
end
```
### Trial Event Hooks
You can define methods that will be called at the same time as experiment
alternative participation and goal completion.
For example:
``` ruby
Split.configure do |config|
config.on_trial = :log_trial # run on every trial
config.on_trial_choose = :log_trial_choose # run on trials with new users only
config.on_trial_complete = :log_trial_complete
end
```
Set these attributes to a method name available in the same context as the
`ab_test` method. These methods should accept one argument, a `Trial` instance.
``` ruby
def log_trial(trial)
logger.info "experiment=%s alternative=%s user=%s" %
[ trial.experiment.name, trial.alternative, current_user.id ]
end
def log_trial_choose(trial)
logger.info "[new user] experiment=%s alternative=%s user=%s" %
[ trial.experiment.name, trial.alternative, current_user.id ]
end
def log_trial_complete(trial)
logger.info "experiment=%s alternative=%s user=%s complete=true" %
[ trial.experiment.name, trial.alternative, current_user.id ]
end
```
#### Views
If you are running `ab_test` from a view, you must define your event
hook callback as a
[helper_method](https://apidock.com/rails/AbstractController/Helpers/ClassMethods/helper_method)
in the controller:
``` ruby
helper_method :log_trial_choose
def log_trial_choose(trial)
logger.info "experiment=%s alternative=%s user=%s" %
[ trial.experiment.name, trial.alternative, current_user.id ]
end
```
### Experiment Hooks
You can assign a proc that will be called when an experiment is reset or deleted. You can use these hooks to call methods within your application to keep data related to experiments in sync with Split.
For example:
``` ruby
Split.configure do |config|
# after experiment reset or deleted
config.on_experiment_reset = -> (example) { # Do something on reset }
config.on_experiment_delete = -> (experiment) { # Do something else on delete }
# before experiment reset or deleted
config.on_before_experiment_reset = -> (example) { # Do something on reset }
config.on_before_experiment_delete = -> (experiment) { # Do something else on delete }
# after experiment winner had been set
config.on_experiment_winner_choose = -> (experiment) { # Do something on winner choose }
end
```
## Web Interface
Split comes with a Sinatra-based front end to get an overview of how your experiments are doing.
If you are running Rails 2: You can mount this inside your app using Rack::URLMap in your `config.ru`
```ruby
require 'split/dashboard'
run Rack::URLMap.new \
"/" => Your::App.new,
"/split" => Split::Dashboard.new
```
However, if you are using Rails 3 or higher: You can mount this inside your app routes by first adding this to the Gemfile:
```ruby
gem 'split', require: 'split/dashboard'
```
Then adding this to config/routes.rb
```ruby
mount Split::Dashboard, at: 'split'
```
You may want to password protect that page, you can do so with `Rack::Auth::Basic` (in your split initializer file)
```ruby
# Rails apps or apps that already depend on activesupport
Split::Dashboard.use Rack::Auth::Basic do |username, password|
# Protect against timing attacks:
# - Use & (do not use &&) so that it doesn't short circuit.
# - Use digests to stop length information leaking
ActiveSupport::SecurityUtils.secure_compare(::Digest::SHA256.hexdigest(username), ::Digest::SHA256.hexdigest(ENV["SPLIT_USERNAME"])) &
ActiveSupport::SecurityUtils.secure_compare(::Digest::SHA256.hexdigest(password), ::Digest::SHA256.hexdigest(ENV["SPLIT_PASSWORD"]))
end
# Apps without activesupport
Split::Dashboard.use Rack::Auth::Basic do |username, password|
# Protect against timing attacks:
# - Use & (do not use &&) so that it doesn't short circuit.
# - Use digests to stop length information leaking
Rack::Utils.secure_compare(::Digest::SHA256.hexdigest(username), ::Digest::SHA256.hexdigest(ENV["SPLIT_USERNAME"])) &
Rack::Utils.secure_compare(::Digest::SHA256.hexdigest(password), ::Digest::SHA256.hexdigest(ENV["SPLIT_PASSWORD"]))
end
```
You can even use Devise or any other Warden-based authentication method to authorize users. Just replace `mount Split::Dashboard, :at => 'split'` in `config/routes.rb` with the following:
```ruby
match "/split" => Split::Dashboard, anchor: false, via: [:get, :post, :delete], constraints: -> (request) do
request.env['warden'].authenticated? # are we authenticated?
request.env['warden'].authenticate! # authenticate if not already
# or even check any other condition such as request.env['warden'].user.is_admin?
end
```
More information on this [here](https://steve.dynedge.co.uk/2011/12/09/controlling-access-to-routes-and-rack-apps-in-rails-3-with-devise-and-warden/)
### Screenshot

## Configuration
You can override the default configuration options of Split like so:
```ruby
Split.configure do |config|
config.db_failover = true # handle Redis errors gracefully
config.db_failover_on_db_error = -> (error) { Rails.logger.error(error.message) }
config.allow_multiple_experiments = true
config.enabled = true
config.persistence = Split::Persistence::SessionAdapter
#config.start_manually = false ## new test will have to be started manually from the admin panel. default false
#config.reset_manually = false ## if true, it never resets the experiment data, even if the configuration changes
config.include_rails_helper = true
config.redis = "redis://custom.redis.url:6380"
end
```
Split looks for the Redis host in the environment variable `REDIS_URL` then
defaults to `redis://localhost:6379` if not specified by configure block.
On platforms like Heroku, Split will use the value of `REDIS_PROVIDER` to
determine which env variable key to use when retrieving the host config. This
defaults to `REDIS_URL`.
### Filtering
In most scenarios you don't want to have AB-Testing enabled for web spiders, robots or special groups of users.
Split provides functionality to filter this based on a predefined, extensible list of bots, IP-lists or custom exclude logic.
```ruby
Split.configure do |config|
# bot config
config.robot_regex = /my_custom_robot_regex/ # or
config.bots['newbot'] = "Description for bot with 'newbot' user agent, which will be added to config.robot_regex for exclusion"
# IP config
config.ignore_ip_addresses << '81.19.48.130' # or regex: /81\.19\.48\.[0-9]+/
# or provide your own filter functionality, the default is proc{ |request| is_robot? || is_ignored_ip_address? || is_preview? }
config.ignore_filter = -> (request) { CustomExcludeLogic.excludes?(request) }
end
```
### Experiment configuration
Instead of providing the experiment options inline, you can store them
in a hash. This hash can control your experiment's alternatives, weights,
algorithm and if the experiment resets once finished:
```ruby
Split.configure do |config|
config.experiments = {
my_first_experiment: {
alternatives: ["a", "b"],
resettable: false
},
:my_second_experiment => {
algorithm: 'Split::Algorithms::Whiplash',
alternatives: [
{ name: "a", percent: 67 },
{ name: "b", percent: 33 }
]
}
}
end
```
You can also store your experiments in a YAML file:
```ruby
Split.configure do |config|
config.experiments = YAML.load_file "config/experiments.yml"
end
```
You can then define the YAML file like:
```yaml
my_first_experiment:
alternatives:
- a
- b
my_second_experiment:
alternatives:
- name: a
percent: 67
- name: b
percent: 33
resettable: false
```
This simplifies the calls from your code:
```ruby
ab_test(:my_first_experiment)
```
and:
```ruby
ab_finished(:my_first_experiment)
```
You can also add meta data for each experiment, which is very useful when you need more than an alternative name to change behaviour:
```ruby
Split.configure do |config|
config.experiments = {
my_first_experiment: {
alternatives: ["a", "b"],
metadata: {
"a" => {"text" => "Have a fantastic day"},
"b" => {"text" => "Don't get hit by a bus"}
}
}
}
end
```
```yaml
my_first_experiment:
alternatives:
- a
- b
metadata:
a:
text: "Have a fantastic day"
b:
text: "Don't get hit by a bus"
```
This allows for some advanced experiment configuration using methods like:
```ruby
trial.alternative.name # => "a"
trial.metadata['text'] # => "Have a fantastic day"
```
or in views:
```erb
<% ab_test("my_first_experiment") do |alternative, meta| %>
<%= alternative %>
<small><%= meta['text'] %></small>
<% end %>
```
The keys used in meta data should be Strings
#### Metrics
You might wish to track generic metrics, such as conversions, and use
those to complete multiple different experiments without adding more to
your code. You can use the configuration hash to do this, thanks to
the `:metric` option.
```ruby
Split.configure do |config|
config.experiments = {
my_first_experiment: {
alternatives: ["a", "b"],
metric: :my_metric
}
}
end
```
Your code may then track a completion using the metric instead of
the experiment name:
```ruby
ab_finished(:my_metric)
```
You can also create a new metric by instantiating and saving a new Metric object.
```ruby
Split::Metric.new(:my_metric)
Split::Metric.save
```
#### Goals
You might wish to allow an experiment to have multiple, distinguishable goals.
The API to define goals for an experiment is this:
```ruby
ab_test({link_color: ["purchase", "refund"]}, "red", "blue")
```
or you can define them in a configuration file:
```ruby
Split.configure do |config|
config.experiments = {
link_color: {
alternatives: ["red", "blue"],
goals: ["purchase", "refund"]
}
}
end
```
To complete a goal conversion, you do it like:
```ruby
ab_finished(link_color: "purchase")
```
Note that if you pass additional options, that should be a separate hash:
```ruby
ab_finished({ link_color: "purchase" }, reset: false)
```
**NOTE:** This does not mean that a single experiment can complete more than one goal.
Once you finish one of the goals, the test is considered to be completed, and finishing the other goal will no longer register. (Assuming the test runs with `reset: false`.)
**Good Example**: Test if listing Plan A first result in more conversions to Plan A (goal: "plana_conversion") or Plan B (goal: "planb_conversion").
**Bad Example**: Test if button color increases conversion rate through multiple steps of a funnel. THIS WILL NOT WORK.
**Bad Example**: Test both how button color affects signup *and* how it affects login, at the same time. THIS WILL NOT WORK.
#### Combined Experiments
If you want to test how button color affects signup *and* how it affects login at the same time, use combined experiments.
Configure like so:
```ruby
Split.configuration.experiments = {
:button_color_experiment => {
:alternatives => ["blue", "green"],
:combined_experiments => ["button_color_on_signup", "button_color_on_login"]
}
}
```
Starting the combined test starts all combined experiments
```ruby
ab_combined_test(:button_color_experiment)
```
Finish each combined test as normal
```ruby
ab_finished(:button_color_on_login)
ab_finished(:button_color_on_signup)
```
**Additional Configuration**:
* Be sure to enable `allow_multiple_experiments`
* In Sinatra include the CombinedExperimentsHelper
```
helpers Split::CombinedExperimentsHelper
```
### DB failover solution
Due to the fact that Redis has no automatic failover mechanism, it's
possible to switch on the `db_failover` config option, so that `ab_test`
and `ab_finished` will not crash in case of a db failure. `ab_test` always
delivers alternative A (the first one) in that case.
It's also possible to set a `db_failover_on_db_error` callback (proc)
for example to log these errors via Rails.logger.
### Redis
You may want to change the Redis host and port Split connects to, or
set various other options at startup.
Split has a `redis` setter which can be given a string or a Redis
object. This means if you're already using Redis in your app, Split
can re-use the existing connection.
String: `Split.redis = 'redis://localhost:6379'`
Redis: `Split.redis = $redis`
For our rails app we have a `config/initializers/split.rb` file where
we load `config/split.yml` by hand and set the Redis information
appropriately.
Here's our `config/split.yml`:
```yml
development: redis://localhost:6379
test: redis://localhost:6379
staging: redis://redis1.example.com:6379
fi: redis://localhost:6379
production: redis://redis1.example.com:6379
```
And our initializer:
```ruby
split_config = YAML.load_file(Rails.root.join('config', 'split.yml'))
Split.redis = split_config[Rails.env]
```
### Redis Caching (v4.0+)
In some high-volume usage scenarios, Redis load can be incurred by repeated
fetches for fairly static data. Enabling caching will reduce this load.
```ruby
Split.configuration.cache = true
````
This currently caches:
- `Split::ExperimentCatalog.find`
- `Split::Experiment.start_time`
- `Split::Experiment.winner`
## Namespaces
If you're running multiple, separate instances of Split you may want
to namespace the keyspaces so they do not overlap. This is not unlike
the approach taken by many memcached clients.
This feature can be provided by the [redis-namespace](https://github.com/defunkt/redis-namespace)
library. To configure Split to use `Redis::Namespace`, do the following:
1. Add `redis-namespace` to your Gemfile:
```ruby
gem 'redis-namespace'
```
2. Configure `Split.redis` to use a `Redis::Namespace` instance (possible in an
initializer):
```ruby
redis = Redis.new(url: ENV['REDIS_URL']) # or whatever config you want
Split.redis = Redis::Namespace.new(:your_namespace, redis: redis)
```
## Outside of a Web Session
Split provides the Helper module to facilitate running experiments inside web sessions.
Alternatively, you can access the underlying Metric, Trial, Experiment and Alternative objects to
conduct experiments that are not tied to a web session.
```ruby
# create a new experiment
experiment = Split::ExperimentCatalog.find_or_create('color', 'red', 'blue')
# create a new trial
trial = Split::Trial.new(:experiment => experiment)
# run trial
trial.choose!
# get the result, returns either red or blue
trial.alternative.name
# if the goal has been achieved, increment the successful completions for this alternative.
if goal_achieved?
trial.complete!
end
```
## Algorithms
By default, Split ships with `Split::Algorithms::WeightedSample` that randomly selects from possible alternatives for a traditional a/b test.
It is possible to specify static weights to favor certain alternatives.
`Split::Algorithms::Whiplash` is an implementation of a [multi-armed bandit algorithm](http://stevehanov.ca/blog/index.php?id=132).
This algorithm will automatically weight the alternatives based on their relative performance,
choosing the better-performing ones more often as trials are completed.
`Split::Algorithms::BlockRandomization` is an algorithm that ensures equal
participation across all alternatives. This algorithm will choose the alternative
with the fewest participants. In the event of multiple minimum participant alternatives
(i.e. starting a new "Block") the algorithm will choose a random alternative from
those minimum participant alternatives.
Users may also write their own algorithms. The default algorithm may be specified globally in the configuration file, or on a per experiment basis using the experiments hash of the configuration file.
To change the algorithm globally for all experiments, use the following in your initializer:
```ruby
Split.configure do |config|
config.algorithm = Split::Algorithms::Whiplash
end
```
## Extensions
- [Split::Export](https://github.com/splitrb/split-export) - Easily export A/B test data out of Split.
- [Split::Analytics](https://github.com/splitrb/split-analytics) - Push test data to Google Analytics.
- [Split::Mongoid](https://github.com/MongoHQ/split-mongoid) - Store experiment data in mongoid (still uses redis).
- [Split::Cacheable](https://github.com/harrystech/split_cacheable) - Automatically create cache buckets per test.
- [Split::Counters](https://github.com/bernardkroes/split-counters) - Add counters per experiment and alternative.
- [Split::Cli](https://github.com/craigmcnamara/split-cli) - A CLI to trigger Split A/B tests.
## Screencast
Ryan bates has produced an excellent 10 minute screencast about split on the Railscasts site: [A/B Testing with Split](http://railscasts.com/episodes/331-a-b-testing-with-split)
## Blogposts
* [Recipe: A/B testing with KISSMetrics and the split gem](https://robots.thoughtbot.com/post/9595887299/recipe-a-b-testing-with-kissmetrics-and-the-split-gem)
* [Rails A/B testing with Split on Heroku](http://blog.nathanhumbert.com/2012/02/rails-ab-testing-with-split-on-heroku.html)
## Backers
Support us with a monthly donation and help us continue our activities. [[Become a backer](https://opencollective.com/split#backer)]
<a href="https://opencollective.com/split/backer/0/website" target="_blank"><img src="https://opencollective.com/split/backer/0/avatar.svg"></a>
<a href="https://opencollective.com/split/backer/1/website" target="_blank"><img src="https://opencollective.com/split/backer/1/avatar.svg"></a>
<a href="https://opencollective.com/split/backer/2/website" target="_blank"><img src="https://opencollective.com/split/backer/2/avatar.svg"></a>
<a href="https://opencollective.com/split/backer/3/website" target="_blank"><img src="https://opencollective.com/split/backer/3/avatar.svg"></a>
<a href="https://opencollective.com/split/backer/4/website" target="_blank"><img src="https://opencollective.com/split/backer/4/avatar.svg"></a>
<a href="https://opencollective.com/split/backer/5/website" target="_blank"><img src="https://opencollective.com/split/backer/5/avatar.svg"></a>
<a href="https://opencollective.com/split/backer/6/website" target="_blank"><img src="https://opencollective.com/split/backer/6/avatar.svg"></a>
<a href="https://opencollective.com/split/backer/7/website" target="_blank"><img src="https://opencollective.com/split/backer/7/avatar.svg"></a>
<a href="https://opencollective.com/split/backer/8/website" target="_blank"><img src="https://opencollective.com/split/backer/8/avatar.svg"></a>
<a href="https://opencollective.com/split/backer/9/website" target="_blank"><img src="https://opencollective.com/split/backer/9/avatar.svg"></a>
<a href="https://opencollective.com/split/backer/10/website" target="_blank"><img src="https://opencollective.com/split/backer/10/avatar.svg"></a>
<a href="https://opencollective.com/split/backer/11/website" target="_blank"><img src="https://opencollective.com/split/backer/11/avatar.svg"></a>
<a href="https://opencollective.com/split/backer/12/website" target="_blank"><img src="https://opencollective.com/split/backer/12/avatar.svg"></a>
<a href="https://opencollective.com/split/backer/13/website" target="_blank"><img src="https://opencollective.com/split/backer/13/avatar.svg"></a>
<a href="https://opencollective.com/split/backer/14/website" target="_blank"><img src="https://opencollective.com/split/backer/14/avatar.svg"></a>
<a href="https://opencollective.com/split/backer/15/website" target="_blank"><img src="https://opencollective.com/split/backer/15/avatar.svg"></a>
<a href="https://opencollective.com/split/backer/16/website" target="_blank"><img src="https://opencollective.com/split/backer/16/avatar.svg"></a>
<a href="https://opencollective.com/split/backer/17/website" target="_blank"><img src="https://opencollective.com/split/backer/17/avatar.svg"></a>
<a href="https://opencollective.com/split/backer/18/website" target="_blank"><img src="https://opencollective.com/split/backer/18/avatar.svg"></a>
<a href="https://opencollective.com/split/backer/19/website" target="_blank"><img src="https://opencollective.com/split/backer/19/avatar.svg"></a>
<a href="https://opencollective.com/split/backer/20/website" target="_blank"><img src="https://opencollective.com/split/backer/20/avatar.svg"></a>
<a href="https://opencollective.com/split/backer/21/website" target="_blank"><img src="https://opencollective.com/split/backer/21/avatar.svg"></a>
<a href="https://opencollective.com/split/backer/22/website" target="_blank"><img src="https://opencollective.com/split/backer/22/avatar.svg"></a>
<a href="https://opencollective.com/split/backer/23/website" target="_blank"><img src="https://opencollective.com/split/backer/23/avatar.svg"></a>
<a href="https://opencollective.com/split/backer/24/website" target="_blank"><img src="https://opencollective.com/split/backer/24/avatar.svg"></a>
<a href="https://opencollective.com/split/backer/25/website" target="_blank"><img src="https://opencollective.com/split/backer/25/avatar.svg"></a>
<a href="https://opencollective.com/split/backer/26/website" target="_blank"><img src="https://opencollective.com/split/backer/26/avatar.svg"></a>
<a href="https://opencollective.com/split/backer/27/website" target="_blank"><img src="https://opencollective.com/split/backer/27/avatar.svg"></a>
<a href="https://opencollective.com/split/backer/28/website" target="_blank"><img src="https://opencollective.com/split/backer/28/avatar.svg"></a>
<a href="https://opencollective.com/split/backer/29/website" target="_blank"><img src="https://opencollective.com/split/backer/29/avatar.svg"></a>
## 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/split#sponsor)]
<a href="https://opencollective.com/split/sponsor/0/website" target="_blank"><img src="https://opencollective.com/split/sponsor/0/avatar.svg"></a>
<a href="https://opencollective.com/split/sponsor/1/website" target="_blank"><img src="https://opencollective.com/split/sponsor/1/avatar.svg"></a>
<a href="https://opencollective.com/split/sponsor/2/website" target="_blank"><img src="https://opencollective.com/split/sponsor/2/avatar.svg"></a>
<a href="https://opencollective.com/split/sponsor/3/website" target="_blank"><img src="https://opencollective.com/split/sponsor/3/avatar.svg"></a>
<a href="https://opencollective.com/split/sponsor/4/website" target="_blank"><img src="https://opencollective.com/split/sponsor/4/avatar.svg"></a>
<a href="https://opencollective.com/split/sponsor/5/website" target="_blank"><img src="https://opencollective.com/split/sponsor/5/avatar.svg"></a>
<a href="https://opencollective.com/split/sponsor/6/website" target="_blank"><img src="https://opencollective.com/split/sponsor/6/avatar.svg"></a>
<a href="https://opencollective.com/split/sponsor/7/website" target="_blank"><img src="https://opencollective.com/split/sponsor/7/avatar.svg"></a>
<a href="https://opencollective.com/split/sponsor/8/website" target="_blank"><img src="https://opencollective.com/split/sponsor/8/avatar.svg"></a>
<a href="https://opencollective.com/split/sponsor/9/website" target="_blank"><img src="https://opencollective.com/split/sponsor/9/avatar.svg"></a>
<a href="https://opencollective.com/split/sponsor/10/website" target="_blank"><img src="https://opencollective.com/split/sponsor/10/avatar.svg"></a>
<a href="https://opencollective.com/split/sponsor/11/website" target="_blank"><img src="https://opencollective.com/split/sponsor/11/avatar.svg"></a>
<a href="https://opencollective.com/split/sponsor/12/website" target="_blank"><img src="https://opencollective.com/split/sponsor/12/avatar.svg"></a>
<a href="https://opencollective.com/split/sponsor/13/website" target="_blank"><img src="https://opencollective.com/split/sponsor/13/avatar.svg"></a>
<a href="https://opencollective.com/split/sponsor/14/website" target="_blank"><img src="https://opencollective.com/split/sponsor/14/avatar.svg"></a>
<a href="https://opencollective.com/split/sponsor/15/website" target="_blank"><img src="https://opencollective.com/split/sponsor/15/avatar.svg"></a>
<a href="https://opencollective.com/split/sponsor/16/website" target="_blank"><img src="https://opencollective.com/split/sponsor/16/avatar.svg"></a>
<a href="https://opencollective.com/split/sponsor/17/website" target="_blank"><img src="https://opencollective.com/split/sponsor/17/avatar.svg"></a>
<a href="https://opencollective.com/split/sponsor/18/website" target="_blank"><img src="https://opencollective.com/split/sponsor/18/avatar.svg"></a>
<a href="https://opencollective.com/split/sponsor/19/website" target="_blank"><img src="https://opencollective.com/split/sponsor/19/avatar.svg"></a>
<a href="https://opencollective.com/split/sponsor/20/website" target="_blank"><img src="https://opencollective.com/split/sponsor/20/avatar.svg"></a>
<a href="https://opencollective.com/split/sponsor/21/website" target="_blank"><img src="https://opencollective.com/split/sponsor/21/avatar.svg"></a>
<a href="https://opencollective.com/split/sponsor/22/website" target="_blank"><img src="https://opencollective.com/split/sponsor/22/avatar.svg"></a>
<a href="https://opencollective.com/split/sponsor/23/website" target="_blank"><img src="https://opencollective.com/split/sponsor/23/avatar.svg"></a>
<a href="https://opencollective.com/split/sponsor/24/website" target="_blank"><img src="https://opencollective.com/split/sponsor/24/avatar.svg"></a>
<a href="https://opencollective.com/split/sponsor/25/website" target="_blank"><img src="https://opencollective.com/split/sponsor/25/avatar.svg"></a>
<a href="https://opencollective.com/split/sponsor/26/website" target="_blank"><img src="https://opencollective.com/split/sponsor/26/avatar.svg"></a>
<a href="https://opencollective.com/split/sponsor/27/website" target="_blank"><img src="https://opencollective.com/split/sponsor/27/avatar.svg"></a>
<a href="https://opencollective.com/split/sponsor/28/website" target="_blank"><img src="https://opencollective.com/split/sponsor/28/avatar.svg"></a>
<a href="https://opencollective.com/split/sponsor/29/website" target="_blank"><img src="https://opencollective.com/split/sponsor/29/avatar.svg"></a>
## Contribute
Please do! Over 70 different people have contributed to the project, you can see them all here: https://github.com/splitrb/split/graphs/contributors.
### Development
The source code is hosted at [GitHub](https://github.com/splitrb/split).
Report issues and feature requests on [GitHub Issues](https://github.com/splitrb/split/issues).
You can find a discussion form on [Google Groups](https://groups.google.com/d/forum/split-ruby).
### Tests
Run the tests like this:
# Start a Redis server in another tab.
redis-server
bundle
rake spec
### A Note on Patches and Pull Requests
* Fork the project.
* Make your feature addition or bug fix.
* Add tests for it. This is important so I don't break it in a
future version unintentionally.
* Add documentation if necessary.
* Commit. Do not mess with the rakefile, version, or history.
(If you want to have your own version, that is fine. But bump the version in a commit by itself, which I can ignore when I pull.)
* Send a pull request. Bonus points for topic branches.
### Code of Conduct
Please note that this project is released with a [Contributor Code of Conduct](CODE_OF_CONDUCT.md). By participating in this project you agree to abide by its terms.
## Copyright
[MIT License](LICENSE) © 2019 [Andrew Nesbitt](https://github.com/andrew).
<MSG> Merge pull request #308 from jordelver/fix-image-helper-name
Fix image tag helper name
<DFF> @@ -87,7 +87,7 @@ Example: View
```erb
<% ab_test("login_button", "/images/button1.jpg", "/images/button2.jpg") do |button_file| %>
- <%= img_tag(button_file, :alt => "Login!") %>
+ <%= image_tag(button_file, :alt => "Login!") %>
<% end %>
```
| 1 | Merge pull request #308 from jordelver/fix-image-helper-name | 1 | .md | md | mit | splitrb/split |
10071872 | <NME> README.md
<BEF> # [Split](https://libraries.io/rubygems/split)
[](http://badge.fury.io/rb/split)

[](https://codeclimate.com/github/splitrb/split)
[](https://codeclimate.com/github/splitrb/split/coverage)
[](https://github.com/RichardLitt/standard-readme)
[](https://www.codetriage.com/splitrb/split)
> 📈 The Rack Based A/B testing framework https://libraries.io/rubygems/split
Split is a rack based A/B testing framework designed to work with Rails, Sinatra or any other rack based app.
Split is heavily inspired by the [Abingo](https://github.com/ryanb/abingo) and [Vanity](https://github.com/assaf/vanity) Rails A/B testing plugins and [Resque](https://github.com/resque/resque) in its use of Redis.
Split is designed to be hacker friendly, allowing for maximum customisation and extensibility.
## Install
### Requirements
Split v4.0+ is currently tested with Ruby >= 2.5 and Rails >= 5.2.
If your project requires compatibility with Ruby 2.4.x or older Rails versions. You can try v3.0 or v0.8.0(for Ruby 1.9.3)
Split uses Redis as a datastore.
Split only supports Redis 4.0 or greater.
If you're on OS X, Homebrew is the simplest way to install Redis:
```bash
brew install redis
redis-server /usr/local/etc/redis.conf
```
You now have a Redis daemon running on port `6379`.
### Setup
```bash
gem install split
```
#### Rails
Adding `gem 'split'` to your Gemfile will autoload it when rails starts up, as long as you've configured Redis it will 'just work'.
#### Sinatra
To configure Sinatra with Split you need to enable sessions and mix in the helper methods. Add the following lines at the top of your Sinatra app:
```ruby
require 'split'
class MySinatraApp < Sinatra::Base
enable :sessions
helpers Split::Helper
get '/' do
...
end
```
## Usage
To begin your A/B test use the `ab_test` method, naming your experiment with the first argument and then the different alternatives which you wish to test on as the other arguments.
`ab_test` returns one of the alternatives, if a user has already seen that test they will get the same alternative as before, which you can use to split your code on.
It can be used to render different templates, show different text or any other case based logic.
`ab_finished` is used to make a completion of an experiment, or conversion.
Example: View
```erb
<% ab_test(:login_button, "/images/button1.jpg", "/images/button2.jpg") do |button_file| %>
<%= image_tag(button_file, alt: "Login!") %>
<% end %>
```
Example: Controller
```ruby
def register_new_user
```erb
<% ab_test("login_button", "/images/button1.jpg", "/images/button2.jpg") do |button_file| %>
<%= img_tag(button_file, :alt => "Login!") %>
<% end %>
```
```ruby
def buy_new_points
# some business logic
ab_finished(:new_user_free_points)
end
```
Example: Conversion tracking (in a view)
```erb
Thanks for signing up, dude! <% ab_finished(:signup_page_redesign) %>
```
You can find more examples, tutorials and guides on the [wiki](https://github.com/splitrb/split/wiki).
## Statistical Validity
Split has two options for you to use to determine which alternative is the best.
The first option (default on the dashboard) uses a z test (n>30) for the difference between your control and alternative conversion rates to calculate statistical significance. This test will tell you whether an alternative is better or worse than your control, but it will not distinguish between which alternative is the best in an experiment with multiple alternatives. Split will only tell you if your experiment is 90%, 95%, or 99% significant, and this test only works if you have more than 30 participants and 5 conversions for each branch.
As per this [blog post](https://www.evanmiller.org/how-not-to-run-an-ab-test.html) on the pitfalls of A/B testing, it is highly recommended that you determine your requisite sample size for each branch before running the experiment. Otherwise, you'll have an increased rate of false positives (experiments which show a significant effect where really there is none).
[Here](https://www.evanmiller.org/ab-testing/sample-size.html) is a sample size calculator for your convenience.
The second option uses simulations from a beta distribution to determine the probability that the given alternative is the winner compared to all other alternatives. You can view these probabilities by clicking on the drop-down menu labeled "Confidence." This option should be used when the experiment has more than just 1 control and 1 alternative. It can also be used for a simple, 2-alternative A/B test.
Calculating the beta-distribution simulations for a large number of experiments can be slow, so the results are cached. You can specify how often they should be recalculated (the default is once per day).
```ruby
Split.configure do |config|
config.winning_alternative_recalculation_interval = 3600 # 1 hour
end
```
## Extras
### Weighted alternatives
Perhaps you only want to show an alternative to 10% of your visitors because it is very experimental or not yet fully load tested.
To do this you can pass a weight with each alternative in the following ways:
```ruby
ab_test(:homepage_design, {'Old' => 18}, {'New' => 2})
ab_test(:homepage_design, 'Old', {'New' => 1.0/9})
ab_test(:homepage_design, {'Old' => 9}, 'New')
```
This will only show the new alternative to visitors 1 in 10 times, the default weight for an alternative is 1.
### Overriding alternatives
For development and testing, you may wish to force your app to always return an alternative.
You can do this by passing it as a parameter in the url.
If you have an experiment called `button_color` with alternatives called `red` and `blue` used on your homepage, a url such as:
http://myawesomesite.com?ab_test[button_color]=red
will always have red buttons. This won't be stored in your session or count towards to results, unless you set the `store_override` configuration option.
In the event you want to disable all tests without having to know the individual experiment names, add a `SPLIT_DISABLE` query parameter.
http://myawesomesite.com?SPLIT_DISABLE=true
It is not required to send `SPLIT_DISABLE=false` to activate Split.
### Rspec Helper
To aid testing with RSpec, write `spec/support/split_helper.rb` and call `use_ab_test(alternatives_by_experiment)` in your specs as instructed below:
```ruby
# Create a file with these contents at 'spec/support/split_helper.rb'
# and ensure it is `require`d in your rails_helper.rb or spec_helper.rb
module SplitHelper
# Force a specific experiment alternative to always be returned:
# use_ab_test(signup_form: "single_page")
#
# Force alternatives for multiple experiments:
# use_ab_test(signup_form: "single_page", pricing: "show_enterprise_prices")
#
def use_ab_test(alternatives_by_experiment)
allow_any_instance_of(Split::Helper).to receive(:ab_test) do |_receiver, experiment, &block|
variant = alternatives_by_experiment.fetch(experiment) { |key| raise "Unknown experiment '#{key}'" }
block.call(variant) unless block.nil?
variant
end
end
end
# Make the `use_ab_test` method available to all specs:
RSpec.configure do |config|
config.include SplitHelper
end
```
Now you can call `use_ab_test(alternatives_by_experiment)` in your specs, for example:
```ruby
it "registers using experimental signup" do
use_ab_test experiment_name: "alternative_name"
post "/signups"
...
end
```
### Starting experiments manually
By default new A/B tests will be active right after deployment. In case you would like to start new test a while after
the deploy, you can do it by setting the `start_manually` configuration option to `true`.
After choosing this option tests won't be started right after deploy, but after pressing the `Start` button in Split admin dashboard. If a test is deleted from the Split dashboard, then it can only be started after pressing the `Start` button whenever being re-initialized.
### Reset after completion
When a user completes a test their session is reset so that they may start the test again in the future.
To stop this behaviour you can pass the following option to the `ab_finished` method:
```ruby
ab_finished(:experiment_name, reset: false)
```
The user will then always see the alternative they started with.
Any old unfinished experiment key will be deleted from the user's data storage if the experiment had been removed or is over and a winner had been chosen. This allows a user to enroll into any new experiment in cases when the `allow_multiple_experiments` config option is set to `false`.
### Reset experiments manually
By default Split automatically resets the experiment whenever it detects the configuration for an experiment has changed (e.g. you call `ab_test` with different alternatives). You can prevent this by setting the option `reset_manually` to `true`.
You may want to do this when you want to change something, like the variants' names, the metadata about an experiment, etc. without resetting everything.
### Multiple experiments at once
By default Split will avoid users participating in multiple experiments at once. This means you are less likely to skew results by adding in more variation to your tests.
To stop this behaviour and allow users to participate in multiple experiments at once set the `allow_multiple_experiments` config option to true like so:
```ruby
Split.configure do |config|
config.allow_multiple_experiments = true
end
```
This will allow the user to participate in any number of experiments and belong to any alternative in each experiment. This has the possible downside of a variation in one experiment influencing the outcome of another.
To address this, setting the `allow_multiple_experiments` config option to 'control' like so:
```ruby
Split.configure do |config|
config.allow_multiple_experiments = 'control'
end
```
For this to work, each and every experiment you define must have an alternative named 'control'. This will allow the user to participate in multiple experiments as long as the user belongs to the alternative 'control' in each experiment. As soon as the user belongs to an alternative named something other than 'control' the user may not participate in any more experiments. Calling ab_test(<other experiments>) will always return the first alternative without adding the user to that experiment.
### Experiment Persistence
Split comes with three built-in persistence adapters for storing users and the alternatives they've been given for each experiment.
By default Split will store the tests for each user in the session.
You can optionally configure Split to use a cookie, Redis, or any custom adapter of your choosing.
#### Cookies
```ruby
Split.configure do |config|
config.persistence = :cookie
end
```
When using the cookie persistence, Split stores data into an anonymous tracking cookie named 'split', which expires in 1 year. To change that, set the `persistence_cookie_length` in the configuration (unit of time in seconds).
```ruby
Split.configure do |config|
config.persistence = :cookie
config.persistence_cookie_length = 2592000 # 30 days
end
```
The data stored consists of the experiment name and the variants the user is in. Example: { "experiment_name" => "variant_a" }
__Note:__ Using cookies depends on `ActionDispatch::Cookies` or any identical API
#### Redis
Using Redis will allow ab_users to persist across sessions or machines.
```ruby
Split.configure do |config|
config.persistence = Split::Persistence::RedisAdapter.with_config(lookup_by: -> (context) { context.current_user_id })
# Equivalent
# config.persistence = Split::Persistence::RedisAdapter.with_config(lookup_by: :current_user_id)
end
```
Options:
* `lookup_by`: method to invoke per request for uniquely identifying ab_users (mandatory configuration)
* `namespace`: separate namespace to store these persisted values (default "persistence")
* `expire_seconds`: sets TTL for user key. (if a user is in multiple experiments most recent update will reset TTL for all their assignments)
#### Dual Adapter
The Dual Adapter allows the use of different persistence adapters for logged-in and logged-out users. A common use case is to use Redis for logged-in users and Cookies for logged-out users.
```ruby
cookie_adapter = Split::Persistence::CookieAdapter
redis_adapter = Split::Persistence::RedisAdapter.with_config(
lookup_by: -> (context) { context.send(:current_user).try(:id) },
expire_seconds: 2592000)
Split.configure do |config|
config.persistence = Split::Persistence::DualAdapter.with_config(
logged_in: -> (context) { !context.send(:current_user).try(:id).nil? },
logged_in_adapter: redis_adapter,
logged_out_adapter: cookie_adapter)
config.persistence_cookie_length = 2592000 # 30 days
end
```
#### Custom Adapter
Your custom adapter needs to implement the same API as existing adapters.
See `Split::Persistence::CookieAdapter` or `Split::Persistence::SessionAdapter` for a starting point.
```ruby
Split.configure do |config|
config.persistence = YourCustomAdapterClass
end
```
### Trial Event Hooks
You can define methods that will be called at the same time as experiment
alternative participation and goal completion.
For example:
``` ruby
Split.configure do |config|
config.on_trial = :log_trial # run on every trial
config.on_trial_choose = :log_trial_choose # run on trials with new users only
config.on_trial_complete = :log_trial_complete
end
```
Set these attributes to a method name available in the same context as the
`ab_test` method. These methods should accept one argument, a `Trial` instance.
``` ruby
def log_trial(trial)
logger.info "experiment=%s alternative=%s user=%s" %
[ trial.experiment.name, trial.alternative, current_user.id ]
end
def log_trial_choose(trial)
logger.info "[new user] experiment=%s alternative=%s user=%s" %
[ trial.experiment.name, trial.alternative, current_user.id ]
end
def log_trial_complete(trial)
logger.info "experiment=%s alternative=%s user=%s complete=true" %
[ trial.experiment.name, trial.alternative, current_user.id ]
end
```
#### Views
If you are running `ab_test` from a view, you must define your event
hook callback as a
[helper_method](https://apidock.com/rails/AbstractController/Helpers/ClassMethods/helper_method)
in the controller:
``` ruby
helper_method :log_trial_choose
def log_trial_choose(trial)
logger.info "experiment=%s alternative=%s user=%s" %
[ trial.experiment.name, trial.alternative, current_user.id ]
end
```
### Experiment Hooks
You can assign a proc that will be called when an experiment is reset or deleted. You can use these hooks to call methods within your application to keep data related to experiments in sync with Split.
For example:
``` ruby
Split.configure do |config|
# after experiment reset or deleted
config.on_experiment_reset = -> (example) { # Do something on reset }
config.on_experiment_delete = -> (experiment) { # Do something else on delete }
# before experiment reset or deleted
config.on_before_experiment_reset = -> (example) { # Do something on reset }
config.on_before_experiment_delete = -> (experiment) { # Do something else on delete }
# after experiment winner had been set
config.on_experiment_winner_choose = -> (experiment) { # Do something on winner choose }
end
```
## Web Interface
Split comes with a Sinatra-based front end to get an overview of how your experiments are doing.
If you are running Rails 2: You can mount this inside your app using Rack::URLMap in your `config.ru`
```ruby
require 'split/dashboard'
run Rack::URLMap.new \
"/" => Your::App.new,
"/split" => Split::Dashboard.new
```
However, if you are using Rails 3 or higher: You can mount this inside your app routes by first adding this to the Gemfile:
```ruby
gem 'split', require: 'split/dashboard'
```
Then adding this to config/routes.rb
```ruby
mount Split::Dashboard, at: 'split'
```
You may want to password protect that page, you can do so with `Rack::Auth::Basic` (in your split initializer file)
```ruby
# Rails apps or apps that already depend on activesupport
Split::Dashboard.use Rack::Auth::Basic do |username, password|
# Protect against timing attacks:
# - Use & (do not use &&) so that it doesn't short circuit.
# - Use digests to stop length information leaking
ActiveSupport::SecurityUtils.secure_compare(::Digest::SHA256.hexdigest(username), ::Digest::SHA256.hexdigest(ENV["SPLIT_USERNAME"])) &
ActiveSupport::SecurityUtils.secure_compare(::Digest::SHA256.hexdigest(password), ::Digest::SHA256.hexdigest(ENV["SPLIT_PASSWORD"]))
end
# Apps without activesupport
Split::Dashboard.use Rack::Auth::Basic do |username, password|
# Protect against timing attacks:
# - Use & (do not use &&) so that it doesn't short circuit.
# - Use digests to stop length information leaking
Rack::Utils.secure_compare(::Digest::SHA256.hexdigest(username), ::Digest::SHA256.hexdigest(ENV["SPLIT_USERNAME"])) &
Rack::Utils.secure_compare(::Digest::SHA256.hexdigest(password), ::Digest::SHA256.hexdigest(ENV["SPLIT_PASSWORD"]))
end
```
You can even use Devise or any other Warden-based authentication method to authorize users. Just replace `mount Split::Dashboard, :at => 'split'` in `config/routes.rb` with the following:
```ruby
match "/split" => Split::Dashboard, anchor: false, via: [:get, :post, :delete], constraints: -> (request) do
request.env['warden'].authenticated? # are we authenticated?
request.env['warden'].authenticate! # authenticate if not already
# or even check any other condition such as request.env['warden'].user.is_admin?
end
```
More information on this [here](https://steve.dynedge.co.uk/2011/12/09/controlling-access-to-routes-and-rack-apps-in-rails-3-with-devise-and-warden/)
### Screenshot

## Configuration
You can override the default configuration options of Split like so:
```ruby
Split.configure do |config|
config.db_failover = true # handle Redis errors gracefully
config.db_failover_on_db_error = -> (error) { Rails.logger.error(error.message) }
config.allow_multiple_experiments = true
config.enabled = true
config.persistence = Split::Persistence::SessionAdapter
#config.start_manually = false ## new test will have to be started manually from the admin panel. default false
#config.reset_manually = false ## if true, it never resets the experiment data, even if the configuration changes
config.include_rails_helper = true
config.redis = "redis://custom.redis.url:6380"
end
```
Split looks for the Redis host in the environment variable `REDIS_URL` then
defaults to `redis://localhost:6379` if not specified by configure block.
On platforms like Heroku, Split will use the value of `REDIS_PROVIDER` to
determine which env variable key to use when retrieving the host config. This
defaults to `REDIS_URL`.
### Filtering
In most scenarios you don't want to have AB-Testing enabled for web spiders, robots or special groups of users.
Split provides functionality to filter this based on a predefined, extensible list of bots, IP-lists or custom exclude logic.
```ruby
Split.configure do |config|
# bot config
config.robot_regex = /my_custom_robot_regex/ # or
config.bots['newbot'] = "Description for bot with 'newbot' user agent, which will be added to config.robot_regex for exclusion"
# IP config
config.ignore_ip_addresses << '81.19.48.130' # or regex: /81\.19\.48\.[0-9]+/
# or provide your own filter functionality, the default is proc{ |request| is_robot? || is_ignored_ip_address? || is_preview? }
config.ignore_filter = -> (request) { CustomExcludeLogic.excludes?(request) }
end
```
### Experiment configuration
Instead of providing the experiment options inline, you can store them
in a hash. This hash can control your experiment's alternatives, weights,
algorithm and if the experiment resets once finished:
```ruby
Split.configure do |config|
config.experiments = {
my_first_experiment: {
alternatives: ["a", "b"],
resettable: false
},
:my_second_experiment => {
algorithm: 'Split::Algorithms::Whiplash',
alternatives: [
{ name: "a", percent: 67 },
{ name: "b", percent: 33 }
]
}
}
end
```
You can also store your experiments in a YAML file:
```ruby
Split.configure do |config|
config.experiments = YAML.load_file "config/experiments.yml"
end
```
You can then define the YAML file like:
```yaml
my_first_experiment:
alternatives:
- a
- b
my_second_experiment:
alternatives:
- name: a
percent: 67
- name: b
percent: 33
resettable: false
```
This simplifies the calls from your code:
```ruby
ab_test(:my_first_experiment)
```
and:
```ruby
ab_finished(:my_first_experiment)
```
You can also add meta data for each experiment, which is very useful when you need more than an alternative name to change behaviour:
```ruby
Split.configure do |config|
config.experiments = {
my_first_experiment: {
alternatives: ["a", "b"],
metadata: {
"a" => {"text" => "Have a fantastic day"},
"b" => {"text" => "Don't get hit by a bus"}
}
}
}
end
```
```yaml
my_first_experiment:
alternatives:
- a
- b
metadata:
a:
text: "Have a fantastic day"
b:
text: "Don't get hit by a bus"
```
This allows for some advanced experiment configuration using methods like:
```ruby
trial.alternative.name # => "a"
trial.metadata['text'] # => "Have a fantastic day"
```
or in views:
```erb
<% ab_test("my_first_experiment") do |alternative, meta| %>
<%= alternative %>
<small><%= meta['text'] %></small>
<% end %>
```
The keys used in meta data should be Strings
#### Metrics
You might wish to track generic metrics, such as conversions, and use
those to complete multiple different experiments without adding more to
your code. You can use the configuration hash to do this, thanks to
the `:metric` option.
```ruby
Split.configure do |config|
config.experiments = {
my_first_experiment: {
alternatives: ["a", "b"],
metric: :my_metric
}
}
end
```
Your code may then track a completion using the metric instead of
the experiment name:
```ruby
ab_finished(:my_metric)
```
You can also create a new metric by instantiating and saving a new Metric object.
```ruby
Split::Metric.new(:my_metric)
Split::Metric.save
```
#### Goals
You might wish to allow an experiment to have multiple, distinguishable goals.
The API to define goals for an experiment is this:
```ruby
ab_test({link_color: ["purchase", "refund"]}, "red", "blue")
```
or you can define them in a configuration file:
```ruby
Split.configure do |config|
config.experiments = {
link_color: {
alternatives: ["red", "blue"],
goals: ["purchase", "refund"]
}
}
end
```
To complete a goal conversion, you do it like:
```ruby
ab_finished(link_color: "purchase")
```
Note that if you pass additional options, that should be a separate hash:
```ruby
ab_finished({ link_color: "purchase" }, reset: false)
```
**NOTE:** This does not mean that a single experiment can complete more than one goal.
Once you finish one of the goals, the test is considered to be completed, and finishing the other goal will no longer register. (Assuming the test runs with `reset: false`.)
**Good Example**: Test if listing Plan A first result in more conversions to Plan A (goal: "plana_conversion") or Plan B (goal: "planb_conversion").
**Bad Example**: Test if button color increases conversion rate through multiple steps of a funnel. THIS WILL NOT WORK.
**Bad Example**: Test both how button color affects signup *and* how it affects login, at the same time. THIS WILL NOT WORK.
#### Combined Experiments
If you want to test how button color affects signup *and* how it affects login at the same time, use combined experiments.
Configure like so:
```ruby
Split.configuration.experiments = {
:button_color_experiment => {
:alternatives => ["blue", "green"],
:combined_experiments => ["button_color_on_signup", "button_color_on_login"]
}
}
```
Starting the combined test starts all combined experiments
```ruby
ab_combined_test(:button_color_experiment)
```
Finish each combined test as normal
```ruby
ab_finished(:button_color_on_login)
ab_finished(:button_color_on_signup)
```
**Additional Configuration**:
* Be sure to enable `allow_multiple_experiments`
* In Sinatra include the CombinedExperimentsHelper
```
helpers Split::CombinedExperimentsHelper
```
### DB failover solution
Due to the fact that Redis has no automatic failover mechanism, it's
possible to switch on the `db_failover` config option, so that `ab_test`
and `ab_finished` will not crash in case of a db failure. `ab_test` always
delivers alternative A (the first one) in that case.
It's also possible to set a `db_failover_on_db_error` callback (proc)
for example to log these errors via Rails.logger.
### Redis
You may want to change the Redis host and port Split connects to, or
set various other options at startup.
Split has a `redis` setter which can be given a string or a Redis
object. This means if you're already using Redis in your app, Split
can re-use the existing connection.
String: `Split.redis = 'redis://localhost:6379'`
Redis: `Split.redis = $redis`
For our rails app we have a `config/initializers/split.rb` file where
we load `config/split.yml` by hand and set the Redis information
appropriately.
Here's our `config/split.yml`:
```yml
development: redis://localhost:6379
test: redis://localhost:6379
staging: redis://redis1.example.com:6379
fi: redis://localhost:6379
production: redis://redis1.example.com:6379
```
And our initializer:
```ruby
split_config = YAML.load_file(Rails.root.join('config', 'split.yml'))
Split.redis = split_config[Rails.env]
```
### Redis Caching (v4.0+)
In some high-volume usage scenarios, Redis load can be incurred by repeated
fetches for fairly static data. Enabling caching will reduce this load.
```ruby
Split.configuration.cache = true
````
This currently caches:
- `Split::ExperimentCatalog.find`
- `Split::Experiment.start_time`
- `Split::Experiment.winner`
## Namespaces
If you're running multiple, separate instances of Split you may want
to namespace the keyspaces so they do not overlap. This is not unlike
the approach taken by many memcached clients.
This feature can be provided by the [redis-namespace](https://github.com/defunkt/redis-namespace)
library. To configure Split to use `Redis::Namespace`, do the following:
1. Add `redis-namespace` to your Gemfile:
```ruby
gem 'redis-namespace'
```
2. Configure `Split.redis` to use a `Redis::Namespace` instance (possible in an
initializer):
```ruby
redis = Redis.new(url: ENV['REDIS_URL']) # or whatever config you want
Split.redis = Redis::Namespace.new(:your_namespace, redis: redis)
```
## Outside of a Web Session
Split provides the Helper module to facilitate running experiments inside web sessions.
Alternatively, you can access the underlying Metric, Trial, Experiment and Alternative objects to
conduct experiments that are not tied to a web session.
```ruby
# create a new experiment
experiment = Split::ExperimentCatalog.find_or_create('color', 'red', 'blue')
# create a new trial
trial = Split::Trial.new(:experiment => experiment)
# run trial
trial.choose!
# get the result, returns either red or blue
trial.alternative.name
# if the goal has been achieved, increment the successful completions for this alternative.
if goal_achieved?
trial.complete!
end
```
## Algorithms
By default, Split ships with `Split::Algorithms::WeightedSample` that randomly selects from possible alternatives for a traditional a/b test.
It is possible to specify static weights to favor certain alternatives.
`Split::Algorithms::Whiplash` is an implementation of a [multi-armed bandit algorithm](http://stevehanov.ca/blog/index.php?id=132).
This algorithm will automatically weight the alternatives based on their relative performance,
choosing the better-performing ones more often as trials are completed.
`Split::Algorithms::BlockRandomization` is an algorithm that ensures equal
participation across all alternatives. This algorithm will choose the alternative
with the fewest participants. In the event of multiple minimum participant alternatives
(i.e. starting a new "Block") the algorithm will choose a random alternative from
those minimum participant alternatives.
Users may also write their own algorithms. The default algorithm may be specified globally in the configuration file, or on a per experiment basis using the experiments hash of the configuration file.
To change the algorithm globally for all experiments, use the following in your initializer:
```ruby
Split.configure do |config|
config.algorithm = Split::Algorithms::Whiplash
end
```
## Extensions
- [Split::Export](https://github.com/splitrb/split-export) - Easily export A/B test data out of Split.
- [Split::Analytics](https://github.com/splitrb/split-analytics) - Push test data to Google Analytics.
- [Split::Mongoid](https://github.com/MongoHQ/split-mongoid) - Store experiment data in mongoid (still uses redis).
- [Split::Cacheable](https://github.com/harrystech/split_cacheable) - Automatically create cache buckets per test.
- [Split::Counters](https://github.com/bernardkroes/split-counters) - Add counters per experiment and alternative.
- [Split::Cli](https://github.com/craigmcnamara/split-cli) - A CLI to trigger Split A/B tests.
## Screencast
Ryan bates has produced an excellent 10 minute screencast about split on the Railscasts site: [A/B Testing with Split](http://railscasts.com/episodes/331-a-b-testing-with-split)
## Blogposts
* [Recipe: A/B testing with KISSMetrics and the split gem](https://robots.thoughtbot.com/post/9595887299/recipe-a-b-testing-with-kissmetrics-and-the-split-gem)
* [Rails A/B testing with Split on Heroku](http://blog.nathanhumbert.com/2012/02/rails-ab-testing-with-split-on-heroku.html)
## Backers
Support us with a monthly donation and help us continue our activities. [[Become a backer](https://opencollective.com/split#backer)]
<a href="https://opencollective.com/split/backer/0/website" target="_blank"><img src="https://opencollective.com/split/backer/0/avatar.svg"></a>
<a href="https://opencollective.com/split/backer/1/website" target="_blank"><img src="https://opencollective.com/split/backer/1/avatar.svg"></a>
<a href="https://opencollective.com/split/backer/2/website" target="_blank"><img src="https://opencollective.com/split/backer/2/avatar.svg"></a>
<a href="https://opencollective.com/split/backer/3/website" target="_blank"><img src="https://opencollective.com/split/backer/3/avatar.svg"></a>
<a href="https://opencollective.com/split/backer/4/website" target="_blank"><img src="https://opencollective.com/split/backer/4/avatar.svg"></a>
<a href="https://opencollective.com/split/backer/5/website" target="_blank"><img src="https://opencollective.com/split/backer/5/avatar.svg"></a>
<a href="https://opencollective.com/split/backer/6/website" target="_blank"><img src="https://opencollective.com/split/backer/6/avatar.svg"></a>
<a href="https://opencollective.com/split/backer/7/website" target="_blank"><img src="https://opencollective.com/split/backer/7/avatar.svg"></a>
<a href="https://opencollective.com/split/backer/8/website" target="_blank"><img src="https://opencollective.com/split/backer/8/avatar.svg"></a>
<a href="https://opencollective.com/split/backer/9/website" target="_blank"><img src="https://opencollective.com/split/backer/9/avatar.svg"></a>
<a href="https://opencollective.com/split/backer/10/website" target="_blank"><img src="https://opencollective.com/split/backer/10/avatar.svg"></a>
<a href="https://opencollective.com/split/backer/11/website" target="_blank"><img src="https://opencollective.com/split/backer/11/avatar.svg"></a>
<a href="https://opencollective.com/split/backer/12/website" target="_blank"><img src="https://opencollective.com/split/backer/12/avatar.svg"></a>
<a href="https://opencollective.com/split/backer/13/website" target="_blank"><img src="https://opencollective.com/split/backer/13/avatar.svg"></a>
<a href="https://opencollective.com/split/backer/14/website" target="_blank"><img src="https://opencollective.com/split/backer/14/avatar.svg"></a>
<a href="https://opencollective.com/split/backer/15/website" target="_blank"><img src="https://opencollective.com/split/backer/15/avatar.svg"></a>
<a href="https://opencollective.com/split/backer/16/website" target="_blank"><img src="https://opencollective.com/split/backer/16/avatar.svg"></a>
<a href="https://opencollective.com/split/backer/17/website" target="_blank"><img src="https://opencollective.com/split/backer/17/avatar.svg"></a>
<a href="https://opencollective.com/split/backer/18/website" target="_blank"><img src="https://opencollective.com/split/backer/18/avatar.svg"></a>
<a href="https://opencollective.com/split/backer/19/website" target="_blank"><img src="https://opencollective.com/split/backer/19/avatar.svg"></a>
<a href="https://opencollective.com/split/backer/20/website" target="_blank"><img src="https://opencollective.com/split/backer/20/avatar.svg"></a>
<a href="https://opencollective.com/split/backer/21/website" target="_blank"><img src="https://opencollective.com/split/backer/21/avatar.svg"></a>
<a href="https://opencollective.com/split/backer/22/website" target="_blank"><img src="https://opencollective.com/split/backer/22/avatar.svg"></a>
<a href="https://opencollective.com/split/backer/23/website" target="_blank"><img src="https://opencollective.com/split/backer/23/avatar.svg"></a>
<a href="https://opencollective.com/split/backer/24/website" target="_blank"><img src="https://opencollective.com/split/backer/24/avatar.svg"></a>
<a href="https://opencollective.com/split/backer/25/website" target="_blank"><img src="https://opencollective.com/split/backer/25/avatar.svg"></a>
<a href="https://opencollective.com/split/backer/26/website" target="_blank"><img src="https://opencollective.com/split/backer/26/avatar.svg"></a>
<a href="https://opencollective.com/split/backer/27/website" target="_blank"><img src="https://opencollective.com/split/backer/27/avatar.svg"></a>
<a href="https://opencollective.com/split/backer/28/website" target="_blank"><img src="https://opencollective.com/split/backer/28/avatar.svg"></a>
<a href="https://opencollective.com/split/backer/29/website" target="_blank"><img src="https://opencollective.com/split/backer/29/avatar.svg"></a>
## 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/split#sponsor)]
<a href="https://opencollective.com/split/sponsor/0/website" target="_blank"><img src="https://opencollective.com/split/sponsor/0/avatar.svg"></a>
<a href="https://opencollective.com/split/sponsor/1/website" target="_blank"><img src="https://opencollective.com/split/sponsor/1/avatar.svg"></a>
<a href="https://opencollective.com/split/sponsor/2/website" target="_blank"><img src="https://opencollective.com/split/sponsor/2/avatar.svg"></a>
<a href="https://opencollective.com/split/sponsor/3/website" target="_blank"><img src="https://opencollective.com/split/sponsor/3/avatar.svg"></a>
<a href="https://opencollective.com/split/sponsor/4/website" target="_blank"><img src="https://opencollective.com/split/sponsor/4/avatar.svg"></a>
<a href="https://opencollective.com/split/sponsor/5/website" target="_blank"><img src="https://opencollective.com/split/sponsor/5/avatar.svg"></a>
<a href="https://opencollective.com/split/sponsor/6/website" target="_blank"><img src="https://opencollective.com/split/sponsor/6/avatar.svg"></a>
<a href="https://opencollective.com/split/sponsor/7/website" target="_blank"><img src="https://opencollective.com/split/sponsor/7/avatar.svg"></a>
<a href="https://opencollective.com/split/sponsor/8/website" target="_blank"><img src="https://opencollective.com/split/sponsor/8/avatar.svg"></a>
<a href="https://opencollective.com/split/sponsor/9/website" target="_blank"><img src="https://opencollective.com/split/sponsor/9/avatar.svg"></a>
<a href="https://opencollective.com/split/sponsor/10/website" target="_blank"><img src="https://opencollective.com/split/sponsor/10/avatar.svg"></a>
<a href="https://opencollective.com/split/sponsor/11/website" target="_blank"><img src="https://opencollective.com/split/sponsor/11/avatar.svg"></a>
<a href="https://opencollective.com/split/sponsor/12/website" target="_blank"><img src="https://opencollective.com/split/sponsor/12/avatar.svg"></a>
<a href="https://opencollective.com/split/sponsor/13/website" target="_blank"><img src="https://opencollective.com/split/sponsor/13/avatar.svg"></a>
<a href="https://opencollective.com/split/sponsor/14/website" target="_blank"><img src="https://opencollective.com/split/sponsor/14/avatar.svg"></a>
<a href="https://opencollective.com/split/sponsor/15/website" target="_blank"><img src="https://opencollective.com/split/sponsor/15/avatar.svg"></a>
<a href="https://opencollective.com/split/sponsor/16/website" target="_blank"><img src="https://opencollective.com/split/sponsor/16/avatar.svg"></a>
<a href="https://opencollective.com/split/sponsor/17/website" target="_blank"><img src="https://opencollective.com/split/sponsor/17/avatar.svg"></a>
<a href="https://opencollective.com/split/sponsor/18/website" target="_blank"><img src="https://opencollective.com/split/sponsor/18/avatar.svg"></a>
<a href="https://opencollective.com/split/sponsor/19/website" target="_blank"><img src="https://opencollective.com/split/sponsor/19/avatar.svg"></a>
<a href="https://opencollective.com/split/sponsor/20/website" target="_blank"><img src="https://opencollective.com/split/sponsor/20/avatar.svg"></a>
<a href="https://opencollective.com/split/sponsor/21/website" target="_blank"><img src="https://opencollective.com/split/sponsor/21/avatar.svg"></a>
<a href="https://opencollective.com/split/sponsor/22/website" target="_blank"><img src="https://opencollective.com/split/sponsor/22/avatar.svg"></a>
<a href="https://opencollective.com/split/sponsor/23/website" target="_blank"><img src="https://opencollective.com/split/sponsor/23/avatar.svg"></a>
<a href="https://opencollective.com/split/sponsor/24/website" target="_blank"><img src="https://opencollective.com/split/sponsor/24/avatar.svg"></a>
<a href="https://opencollective.com/split/sponsor/25/website" target="_blank"><img src="https://opencollective.com/split/sponsor/25/avatar.svg"></a>
<a href="https://opencollective.com/split/sponsor/26/website" target="_blank"><img src="https://opencollective.com/split/sponsor/26/avatar.svg"></a>
<a href="https://opencollective.com/split/sponsor/27/website" target="_blank"><img src="https://opencollective.com/split/sponsor/27/avatar.svg"></a>
<a href="https://opencollective.com/split/sponsor/28/website" target="_blank"><img src="https://opencollective.com/split/sponsor/28/avatar.svg"></a>
<a href="https://opencollective.com/split/sponsor/29/website" target="_blank"><img src="https://opencollective.com/split/sponsor/29/avatar.svg"></a>
## Contribute
Please do! Over 70 different people have contributed to the project, you can see them all here: https://github.com/splitrb/split/graphs/contributors.
### Development
The source code is hosted at [GitHub](https://github.com/splitrb/split).
Report issues and feature requests on [GitHub Issues](https://github.com/splitrb/split/issues).
You can find a discussion form on [Google Groups](https://groups.google.com/d/forum/split-ruby).
### Tests
Run the tests like this:
# Start a Redis server in another tab.
redis-server
bundle
rake spec
### A Note on Patches and Pull Requests
* Fork the project.
* Make your feature addition or bug fix.
* Add tests for it. This is important so I don't break it in a
future version unintentionally.
* Add documentation if necessary.
* Commit. Do not mess with the rakefile, version, or history.
(If you want to have your own version, that is fine. But bump the version in a commit by itself, which I can ignore when I pull.)
* Send a pull request. Bonus points for topic branches.
### Code of Conduct
Please note that this project is released with a [Contributor Code of Conduct](CODE_OF_CONDUCT.md). By participating in this project you agree to abide by its terms.
## Copyright
[MIT License](LICENSE) © 2019 [Andrew Nesbitt](https://github.com/andrew).
<MSG> Merge pull request #308 from jordelver/fix-image-helper-name
Fix image tag helper name
<DFF> @@ -87,7 +87,7 @@ Example: View
```erb
<% ab_test("login_button", "/images/button1.jpg", "/images/button2.jpg") do |button_file| %>
- <%= img_tag(button_file, :alt => "Login!") %>
+ <%= image_tag(button_file, :alt => "Login!") %>
<% end %>
```
| 1 | Merge pull request #308 from jordelver/fix-image-helper-name | 1 | .md | md | mit | splitrb/split |
10071873 | <NME> index.ts
<BEF> type MatchFn = (ch: number) => boolean;
/**
* A streaming, character code-based string reader
*/
export default class Scanner {
/** Current string */
string: string;
/** Current scanner position */
pos: number;
/** Lower range limit where string reader is available */
start: number;
/** Upper range limit where string reader is available */
end: number;
constructor(str: string, start?: number, end?: number) {
if (end == null && typeof str === 'string') {
end = str.length;
}
this.string = str;
this.pos = this.start = start || 0;
this.end = end || 0;
}
/**
* Returns true only if the stream is at the end of the file.
*/
eof(): boolean {
return this.pos >= this.end;
}
/**
* Creates a new stream instance which is limited to given `start` and `end`
* range. E.g. its `eof()` method will look at `end` property, not actual
* stream end
*/
limit(start?: number, end?: number): Scanner {
return new Scanner(this.string, start, end);
}
/**
* Returns the next character code in the stream without advancing it.
* Will return NaN at the end of the file.
*/
peek(): number {
return this.string.charCodeAt(this.pos);
}
/**
* Returns the next character in the stream and advances it.
* Also returns <code>undefined</code> when no more characters are available.
*/
next(): number | undefined {
if (this.pos < this.string.length) {
return this.string.charCodeAt(this.pos++);
}
}
/**
* `match` can be a character code or a function that takes a character code
* and returns a boolean. If the next character in the stream 'matches'
* the given argument, it is consumed and returned.
* Otherwise, `false` is returned.
*/
eat(match: number | MatchFn): boolean {
const ch = this.peek();
const ok = typeof match === 'function' ? match(ch) : ch === match;
if (ok) {
this.next();
}
return ok;
}
/**
* Repeatedly calls <code>eat</code> with the given argument, until it
* fails. Returns <code>true</code> if any characters were eaten.
*/
eatWhile(match: number | MatchFn): boolean {
const start = this.pos;
while (!this.eof() && this.eat(match)) { /* */ }
return this.pos !== start;
}
/**
* Backs up the stream n characters. Backing it up further than the
* start of the current token will cause things to break, so be careful.
*/
backUp(n: number) {
this.pos -= (n || 1);
}
/**
* Get the string between the start of the current token and the
* current stream position.
*/
current(): string {
return this.substring(this.start, this.pos);
}
/**
* Returns substring for given range
*/
substring(start: number, end?: number): string {
return this.string.slice(start, end);
}
/**
* Creates error object with current stream state
*/
error(message: string): StreamReaderError {
return new StreamReaderError(`${message} at ${this.pos + 1}`, this.pos, this.string);
}
}
export class StreamReaderError extends Error {
pos: number;
string: string;
constructor(message: string, pos: number, str: string) {
super(message);
this.pos = pos;
this.string = str;
}
}
export * from './utils';
<MSG> Allow optional `pos` argument in scanner error method
<DFF> @@ -112,12 +112,12 @@ export default class Scanner {
/**
* Creates error object with current stream state
*/
- error(message: string): StreamReaderError {
- return new StreamReaderError(`${message} at ${this.pos + 1}`, this.pos, this.string);
+ error(message: string, pos = this.pos): ScannerError {
+ return new ScannerError(`${message} at ${pos + 1}`, pos, this.string);
}
}
-export class StreamReaderError extends Error {
+export class ScannerError extends Error {
pos: number;
string: string;
| 3 | Allow optional `pos` argument in scanner error method | 3 | .ts | ts | mit | emmetio/emmet |
10071874 | <NME> index.ts
<BEF> type MatchFn = (ch: number) => boolean;
/**
* A streaming, character code-based string reader
*/
export default class Scanner {
/** Current string */
string: string;
/** Current scanner position */
pos: number;
/** Lower range limit where string reader is available */
start: number;
/** Upper range limit where string reader is available */
end: number;
constructor(str: string, start?: number, end?: number) {
if (end == null && typeof str === 'string') {
end = str.length;
}
this.string = str;
this.pos = this.start = start || 0;
this.end = end || 0;
}
/**
* Returns true only if the stream is at the end of the file.
*/
eof(): boolean {
return this.pos >= this.end;
}
/**
* Creates a new stream instance which is limited to given `start` and `end`
* range. E.g. its `eof()` method will look at `end` property, not actual
* stream end
*/
limit(start?: number, end?: number): Scanner {
return new Scanner(this.string, start, end);
}
/**
* Returns the next character code in the stream without advancing it.
* Will return NaN at the end of the file.
*/
peek(): number {
return this.string.charCodeAt(this.pos);
}
/**
* Returns the next character in the stream and advances it.
* Also returns <code>undefined</code> when no more characters are available.
*/
next(): number | undefined {
if (this.pos < this.string.length) {
return this.string.charCodeAt(this.pos++);
}
}
/**
* `match` can be a character code or a function that takes a character code
* and returns a boolean. If the next character in the stream 'matches'
* the given argument, it is consumed and returned.
* Otherwise, `false` is returned.
*/
eat(match: number | MatchFn): boolean {
const ch = this.peek();
const ok = typeof match === 'function' ? match(ch) : ch === match;
if (ok) {
this.next();
}
return ok;
}
/**
* Repeatedly calls <code>eat</code> with the given argument, until it
* fails. Returns <code>true</code> if any characters were eaten.
*/
eatWhile(match: number | MatchFn): boolean {
const start = this.pos;
while (!this.eof() && this.eat(match)) { /* */ }
return this.pos !== start;
}
/**
* Backs up the stream n characters. Backing it up further than the
* start of the current token will cause things to break, so be careful.
*/
backUp(n: number) {
this.pos -= (n || 1);
}
/**
* Get the string between the start of the current token and the
* current stream position.
*/
current(): string {
return this.substring(this.start, this.pos);
}
/**
* Returns substring for given range
*/
substring(start: number, end?: number): string {
return this.string.slice(start, end);
}
/**
* Creates error object with current stream state
*/
error(message: string): StreamReaderError {
return new StreamReaderError(`${message} at ${this.pos + 1}`, this.pos, this.string);
}
}
export class StreamReaderError extends Error {
pos: number;
string: string;
constructor(message: string, pos: number, str: string) {
super(message);
this.pos = pos;
this.string = str;
}
}
export * from './utils';
<MSG> Allow optional `pos` argument in scanner error method
<DFF> @@ -112,12 +112,12 @@ export default class Scanner {
/**
* Creates error object with current stream state
*/
- error(message: string): StreamReaderError {
- return new StreamReaderError(`${message} at ${this.pos + 1}`, this.pos, this.string);
+ error(message: string, pos = this.pos): ScannerError {
+ return new ScannerError(`${message} at ${pos + 1}`, pos, this.string);
}
}
-export class StreamReaderError extends Error {
+export class ScannerError extends Error {
pos: number;
string: string;
| 3 | Allow optional `pos` argument in scanner error method | 3 | .ts | ts | mit | emmetio/emmet |
10071875 | <NME> experiment_spec.rb
<BEF> # frozen_string_literal: true
require "spec_helper"
require "time"
describe Split::Experiment do
def new_experiment(goals = [])
Split::Experiment.new("link_color", alternatives: ["blue", "red", "green"], goals: goals)
end
def alternative(color)
Split::Alternative.new(color, "link_color")
end
let(:experiment) { new_experiment }
let(:blue) { alternative("blue") }
let(:green) { alternative("green") }
context "with an experiment" do
let(:experiment) { Split::Experiment.new("basket_text", alternatives: ["Basket", "Cart"]) }
it "should have a name" do
expect(experiment.name).to eq("basket_text")
end
it "should have alternatives" do
expect(experiment.alternatives.length).to be 2
end
it "should have alternatives with correct names" do
expect(experiment.alternatives.collect { |a| a.name }).to eq(["Basket", "Cart"])
end
it "should be resettable by default" do
expect(experiment.resettable).to be_truthy
end
it "should save to redis" do
experiment.save
expect(Split.redis.exists?("basket_text")).to be true
end
it "should save the start time to redis" do
experiment_start_time = Time.at(1372167761)
expect(Time).to receive(:now).and_return(experiment_start_time)
experiment.save
expect(Split::ExperimentCatalog.find("basket_text").start_time).to eq(experiment_start_time)
end
it "should not save the start time to redis when start_manually is enabled" do
expect(Split.configuration).to receive(:start_manually).and_return(true)
experiment.save
expect(Split::ExperimentCatalog.find("basket_text").start_time).to be_nil
end
it "should save the selected algorithm to redis" do
experiment_algorithm = Split::Algorithms::Whiplash
experiment.algorithm = experiment_algorithm
experiment.save
expect(Split::ExperimentCatalog.find("basket_text").algorithm).to eq(experiment_algorithm)
end
it "should handle having a start time stored as a string" do
experiment_start_time = Time.parse("Sat Mar 03 14:01:03")
expect(Time).to receive(:now).twice.and_return(experiment_start_time)
experiment.save
Split.redis.hset(:experiment_start_times, experiment.name, experiment_start_time.to_s)
expect(Split::ExperimentCatalog.find("basket_text").start_time).to eq(experiment_start_time)
end
it "should handle not having a start time" do
experiment_start_time = Time.parse("Sat Mar 03 14:01:03")
expect(Time).to receive(:now).and_return(experiment_start_time)
experiment.save
Split.redis.hdel(:experiment_start_times, experiment.name)
expect(Split::ExperimentCatalog.find("basket_text").start_time).to be_nil
end
it "should not create duplicates when saving multiple times" do
experiment.save
experiment.save
expect(Split.redis.exists?("basket_text")).to be true
expect(Split.redis.lrange("basket_text", 0, -1)).to eq(['{"Basket":1}', '{"Cart":1}'])
end
describe "new record?" do
it "should know if it hasn't been saved yet" do
expect(experiment.new_record?).to be_truthy
end
it "should know if it has been saved yet" do
experiment.save
expect(experiment.new_record?).to be_falsey
end
end
describe "control" do
it "should be the first alternative" do
experiment.save
expect(experiment.control.name).to eq("Basket")
end
end
end
describe "initialization" do
it "should set the algorithm when passed as an option to the initializer" do
experiment = Split::Experiment.new("basket_text", alternatives: ["Basket", "Cart"], algorithm: Split::Algorithms::Whiplash)
expect(experiment.algorithm).to eq(Split::Algorithms::Whiplash)
end
experiment = Split::Experiment.new('basket_text', :alternatives => ['Basket', "Cart"], :resettable => false)
expect(experiment.resettable).to be_falsey
end
end
describe 'persistent configuration' do
describe "persistent configuration" do
it "should persist resettable in redis" do
experiment = Split::Experiment.new("basket_text", alternatives: ["Basket", "Cart"], resettable: false)
experiment.save
e = Split::ExperimentCatalog.find("basket_text")
expect(e).to eq(experiment)
expect(e.resettable).to be_falsey
end
describe "#metadata" do
let(:experiment) { Split::Experiment.new("basket_text", alternatives: ["Basket", "Cart"], algorithm: Split::Algorithms::Whiplash, metadata: meta) }
let(:meta) { { a: "b" } }
before do
experiment.save
end
it "should delete the key when metadata is removed" do
experiment.metadata = nil
experiment.save
expect(Split.redis.exists?(experiment.metadata_key)).to be_falsey
end
context "simple hash" do
let(:meta) { { "basket" => "a", "cart" => "b" } }
it "should persist metadata in redis" do
e = Split::ExperimentCatalog.find("basket_text")
expect(e).to eq(experiment)
expect(e.metadata).to eq(meta)
end
end
context "nested hash" do
let(:meta) { { "basket" => { "one" => "two" }, "cart" => "b" } }
it "should persist metadata in redis" do
e = Split::ExperimentCatalog.find("basket_text")
expect(e).to eq(experiment)
expect(e.metadata).to eq(meta)
end
end
end
it "should persist algorithm in redis" do
experiment = Split::Experiment.new("basket_text", alternatives: ["Basket", "Cart"], algorithm: Split::Algorithms::Whiplash)
experiment.save
e = Split::ExperimentCatalog.find("basket_text")
expect(e).to eq(experiment)
expect(e.algorithm).to eq(Split::Algorithms::Whiplash)
end
it "should persist a new experiment in redis, that does not exist in the configuration file" do
experiment = Split::Experiment.new("foobar", alternatives: ["tra", "la"], algorithm: Split::Algorithms::Whiplash)
experiment.save
e = Split::ExperimentCatalog.find("foobar")
expect(e).to eq(experiment)
expect(e.alternatives.collect { |a| a.name }).to eq(["tra", "la"])
end
end
describe "deleting" do
it "should delete itself" do
experiment = Split::Experiment.new("basket_text", alternatives: [ "Basket", "Cart"])
experiment.save
experiment.delete
expect(Split.redis.exists?("link_color")).to be false
expect(Split::ExperimentCatalog.find("link_color")).to be_nil
end
it "should increment the version" do
expect(experiment.version).to eq(0)
experiment.delete
expect(experiment.version).to eq(1)
end
it "should call the on_experiment_delete hook" do
expect(Split.configuration.on_experiment_delete).to receive(:call)
experiment.delete
end
it "should call the on_before_experiment_delete hook" do
expect(Split.configuration.on_before_experiment_delete).to receive(:call)
experiment.delete
end
it "should reset the start time if the experiment should be manually started" do
Split.configuration.start_manually = true
experiment.start
experiment.delete
expect(experiment.start_time).to be_nil
end
it "should default cohorting back to false" do
experiment.disable_cohorting
expect(experiment.cohorting_disabled?).to eq(true)
experiment.delete
expect(experiment.cohorting_disabled?).to eq(false)
end
end
describe "winner" do
it "should have no winner initially" do
expect(experiment.winner).to be_nil
end
end
describe "winner=" do
it "should allow you to specify a winner" do
experiment.save
experiment.winner = "red"
expect(experiment.winner.name).to eq("red")
end
it "should call the on_experiment_winner_choose hook" do
expect(Split.configuration.on_experiment_winner_choose).to receive(:call)
experiment.winner = "green"
end
context "when has_winner state is memoized" do
before { expect(experiment).to_not have_winner }
it "should keep has_winner state consistent" do
experiment.winner = "red"
expect(experiment).to have_winner
end
end
end
describe "reset_winner" do
before { experiment.winner = "green" }
it "should reset the winner" do
experiment.reset_winner
expect(experiment.winner).to be_nil
end
context "when has_winner state is memoized" do
before { expect(experiment).to have_winner }
it "should keep has_winner state consistent" do
experiment.reset_winner
expect(experiment).to_not have_winner
end
end
end
describe "has_winner?" do
context "with winner" do
before { experiment.winner = "red" }
it "returns true" do
expect(experiment).to have_winner
end
end
context "without winner" do
it "returns false" do
expect(experiment).to_not have_winner
end
end
it "memoizes has_winner state" do
expect(experiment).to receive(:winner).once
expect(experiment).to_not have_winner
expect(experiment).to_not have_winner
end
end
describe "reset" do
let(:reset_manually) { false }
before do
allow(Split.configuration).to receive(:reset_manually).and_return(reset_manually)
experiment.save
green.increment_participation
green.increment_participation
end
it "should reset all alternatives" do
experiment.winner = "green"
expect(experiment.next_alternative.name).to eq("green")
green.increment_participation
experiment.reset
expect(green.participant_count).to eq(0)
expect(green.completed_count).to eq(0)
end
it "should reset the winner" do
experiment.winner = "green"
expect(experiment.next_alternative.name).to eq("green")
green.increment_participation
experiment.reset
expect(experiment.winner).to be_nil
end
it "should increment the version" do
expect(experiment.version).to eq(0)
experiment.reset
expect(experiment.version).to eq(1)
end
it "should call the on_experiment_reset hook" do
expect(Split.configuration.on_experiment_reset).to receive(:call)
experiment.reset
end
it "should call the on_before_experiment_reset hook" do
expect(Split.configuration.on_before_experiment_reset).to receive(:call)
experiment.reset
end
end
describe "algorithm" do
let(:experiment) { Split::ExperimentCatalog.find_or_create("link_color", "blue", "red", "green") }
it "should use the default algorithm if none is specified" do
expect(experiment.algorithm).to eq(Split.configuration.algorithm)
end
it "should use the user specified algorithm for this experiment if specified" do
experiment.algorithm = Split::Algorithms::Whiplash
expect(experiment.algorithm).to eq(Split::Algorithms::Whiplash)
end
end
describe "#next_alternative" do
context "with multiple alternatives" do
let(:experiment) { Split::ExperimentCatalog.find_or_create("link_color", "blue", "red", "green") }
context "with winner" do
it "should always return the winner" do
green = Split::Alternative.new("green", "link_color")
experiment.winner = "green"
expect(experiment.next_alternative.name).to eq("green")
green.increment_participation
expect(experiment.next_alternative.name).to eq("green")
end
end
context "without winner" do
it "should use the specified algorithm" do
experiment.algorithm = Split::Algorithms::Whiplash
expect(experiment.algorithm).to receive(:choose_alternative).and_return(Split::Alternative.new("green", "link_color"))
expect(experiment.next_alternative.name).to eq("green")
end
end
end
context "with single alternative" do
let(:experiment) { Split::ExperimentCatalog.find_or_create("link_color", "blue") }
it "should always return the only alternative" do
expect(experiment.next_alternative.name).to eq("blue")
expect(experiment.next_alternative.name).to eq("blue")
end
end
end
describe "#cohorting_disabled?" do
it "returns false when nothing has been configured" do
expect(experiment.cohorting_disabled?).to eq false
end
it "returns true when enable_cohorting is performed" do
experiment.enable_cohorting
expect(experiment.cohorting_disabled?).to eq false
end
it "returns false when nothing has been configured" do
experiment.disable_cohorting
expect(experiment.cohorting_disabled?).to eq true
end
end
describe "changing an existing experiment" do
def same_but_different_alternative
Split::ExperimentCatalog.find_or_create("link_color", "blue", "yellow", "orange")
end
it "should reset an experiment if it is loaded with different alternatives" do
experiment.save
blue.participant_count = 5
same_experiment = same_but_different_alternative
expect(same_experiment.alternatives.map(&:name)).to eq(["blue", "yellow", "orange"])
expect(blue.participant_count).to eq(0)
end
it "should only reset once" do
experiment.save
expect(experiment.version).to eq(0)
same_experiment = same_but_different_alternative
expect(same_experiment.version).to eq(1)
same_experiment_again = same_but_different_alternative
expect(same_experiment_again.version).to eq(1)
end
context "when metadata is changed" do
it "should increase version" do
experiment.save
experiment.metadata = { "foo" => "bar" }
expect { experiment.save }.to change { experiment.version }.by(1)
end
it "does not increase version" do
experiment.metadata = nil
experiment.save
expect { experiment.save }.to change { experiment.version }.by(0)
end
end
context "when experiment configuration is changed" do
let(:reset_manually) { false }
before do
experiment.save
allow(Split.configuration).to receive(:reset_manually).and_return(reset_manually)
green.increment_participation
green.increment_participation
experiment.set_alternatives_and_options(alternatives: %w(blue red green zip),
goals: %w(purchase))
experiment.save
end
it "resets all alternatives" do
expect(green.participant_count).to eq(0)
expect(green.completed_count).to eq(0)
end
context "when reset_manually is set" do
let(:reset_manually) { true }
it "does not reset alternatives" do
expect(green.participant_count).to eq(2)
expect(green.completed_count).to eq(0)
end
end
end
end
describe "alternatives passed as non-strings" do
it "should throw an exception if an alternative is passed that is not a string" do
expect { Split::ExperimentCatalog.find_or_create("link_color", :blue, :red) }.to raise_error(ArgumentError)
expect { Split::ExperimentCatalog.find_or_create("link_enabled", true, false) }.to raise_error(ArgumentError)
end
end
describe "specifying weights" do
let(:experiment_with_weight) {
Split::ExperimentCatalog.find_or_create("link_color", { "blue" => 1 }, { "red" => 2 })
}
it "should work for a new experiment" do
expect(experiment_with_weight.alternatives.map(&:weight)).to eq([1, 2])
end
it "should work for an existing experiment" do
experiment.save
expect(experiment_with_weight.alternatives.map(&:weight)).to eq([1, 2])
end
end
describe "specifying goals" do
let(:experiment) {
new_experiment(["purchase"])
}
context "saving experiment" do
let(:same_but_different_goals) { Split::ExperimentCatalog.find_or_create({ "link_color" => ["purchase", "refund"] }, "blue", "red", "green") }
before { experiment.save }
it "can find existing experiment" do
expect(Split::ExperimentCatalog.find("link_color").name).to eq("link_color")
end
it "should reset an experiment if it is loaded with different goals" do
same_but_different_goals
expect(Split::ExperimentCatalog.find("link_color").goals).to eq(["purchase", "refund"])
end
end
it "should have goals" do
expect(experiment.goals).to eq(["purchase"])
end
context "find or create experiment" do
it "should have correct goals" do
experiment = Split::ExperimentCatalog.find_or_create({ "link_color3" => ["purchase", "refund"] }, "blue", "red", "green")
expect(experiment.goals).to eq(["purchase", "refund"])
experiment = Split::ExperimentCatalog.find_or_create("link_color3", "blue", "red", "green")
expect(experiment.goals).to eq([])
end
end
end
describe "beta probability calculation" do
it "should return a hash with the probability of each alternative being the best" do
experiment = Split::ExperimentCatalog.find_or_create("mathematicians", "bernoulli", "poisson", "lagrange")
experiment.calc_winning_alternatives
expect(experiment.alternative_probabilities).not_to be_nil
end
it "should return between 46% and 54% probability for an experiment with 2 alternatives and no data" do
experiment = Split::ExperimentCatalog.find_or_create("scientists", "einstein", "bohr")
experiment.calc_winning_alternatives
expect(experiment.alternatives[0].p_winner).to be_within(0.04).of(0.50)
end
it "should calculate the probability of being the winning alternative separately for each goal", skip: true do
experiment = Split::ExperimentCatalog.find_or_create({ "link_color3" => ["purchase", "refund"] }, "blue", "red", "green")
goal1 = experiment.goals[0]
goal2 = experiment.goals[1]
experiment.alternatives.each do |alternative|
alternative.participant_count = 50
alternative.set_completed_count(10, goal1)
alternative.set_completed_count(15+rand(30), goal2)
end
experiment.calc_winning_alternatives
alt = experiment.alternatives[0]
p_goal1 = alt.p_winner(goal1)
p_goal2 = alt.p_winner(goal2)
expect(p_goal1).not_to be_within(0.04).of(p_goal2)
end
it "should return nil and not re-calculate probabilities if they have already been calculated today" do
experiment = Split::ExperimentCatalog.find_or_create({ "link_color3" => ["purchase", "refund"] }, "blue", "red", "green")
expect(experiment.calc_winning_alternatives).not_to be nil
expect(experiment.calc_winning_alternatives).to be nil
end
end
end
<MSG> Merge pull request #599 from mattwd7/bug-default-experiment-resettable-when-loaded-from-configuration
Respect experiment defaults when loading experiments in initializer.
<DFF> @@ -118,6 +118,23 @@ describe Split::Experiment do
experiment = Split::Experiment.new('basket_text', :alternatives => ['Basket', "Cart"], :resettable => false)
expect(experiment.resettable).to be_falsey
end
+
+ context 'from configuration' do
+ let(:experiment_name) { :my_experiment }
+ let(:experiments) do
+ {
+ experiment_name => {
+ :alternatives => ['Control Opt', 'Alt one']
+ }
+ }
+ end
+
+ before { Split.configuration.experiments = experiments }
+
+ it 'assigns default values to the experiment' do
+ expect(Split::Experiment.new(experiment_name).resettable).to eq(true)
+ end
+ end
end
describe 'persistent configuration' do
| 17 | Merge pull request #599 from mattwd7/bug-default-experiment-resettable-when-loaded-from-configuration | 0 | .rb | rb | mit | splitrb/split |
10071876 | <NME> experiment_spec.rb
<BEF> # frozen_string_literal: true
require "spec_helper"
require "time"
describe Split::Experiment do
def new_experiment(goals = [])
Split::Experiment.new("link_color", alternatives: ["blue", "red", "green"], goals: goals)
end
def alternative(color)
Split::Alternative.new(color, "link_color")
end
let(:experiment) { new_experiment }
let(:blue) { alternative("blue") }
let(:green) { alternative("green") }
context "with an experiment" do
let(:experiment) { Split::Experiment.new("basket_text", alternatives: ["Basket", "Cart"]) }
it "should have a name" do
expect(experiment.name).to eq("basket_text")
end
it "should have alternatives" do
expect(experiment.alternatives.length).to be 2
end
it "should have alternatives with correct names" do
expect(experiment.alternatives.collect { |a| a.name }).to eq(["Basket", "Cart"])
end
it "should be resettable by default" do
expect(experiment.resettable).to be_truthy
end
it "should save to redis" do
experiment.save
expect(Split.redis.exists?("basket_text")).to be true
end
it "should save the start time to redis" do
experiment_start_time = Time.at(1372167761)
expect(Time).to receive(:now).and_return(experiment_start_time)
experiment.save
expect(Split::ExperimentCatalog.find("basket_text").start_time).to eq(experiment_start_time)
end
it "should not save the start time to redis when start_manually is enabled" do
expect(Split.configuration).to receive(:start_manually).and_return(true)
experiment.save
expect(Split::ExperimentCatalog.find("basket_text").start_time).to be_nil
end
it "should save the selected algorithm to redis" do
experiment_algorithm = Split::Algorithms::Whiplash
experiment.algorithm = experiment_algorithm
experiment.save
expect(Split::ExperimentCatalog.find("basket_text").algorithm).to eq(experiment_algorithm)
end
it "should handle having a start time stored as a string" do
experiment_start_time = Time.parse("Sat Mar 03 14:01:03")
expect(Time).to receive(:now).twice.and_return(experiment_start_time)
experiment.save
Split.redis.hset(:experiment_start_times, experiment.name, experiment_start_time.to_s)
expect(Split::ExperimentCatalog.find("basket_text").start_time).to eq(experiment_start_time)
end
it "should handle not having a start time" do
experiment_start_time = Time.parse("Sat Mar 03 14:01:03")
expect(Time).to receive(:now).and_return(experiment_start_time)
experiment.save
Split.redis.hdel(:experiment_start_times, experiment.name)
expect(Split::ExperimentCatalog.find("basket_text").start_time).to be_nil
end
it "should not create duplicates when saving multiple times" do
experiment.save
experiment.save
expect(Split.redis.exists?("basket_text")).to be true
expect(Split.redis.lrange("basket_text", 0, -1)).to eq(['{"Basket":1}', '{"Cart":1}'])
end
describe "new record?" do
it "should know if it hasn't been saved yet" do
expect(experiment.new_record?).to be_truthy
end
it "should know if it has been saved yet" do
experiment.save
expect(experiment.new_record?).to be_falsey
end
end
describe "control" do
it "should be the first alternative" do
experiment.save
expect(experiment.control.name).to eq("Basket")
end
end
end
describe "initialization" do
it "should set the algorithm when passed as an option to the initializer" do
experiment = Split::Experiment.new("basket_text", alternatives: ["Basket", "Cart"], algorithm: Split::Algorithms::Whiplash)
expect(experiment.algorithm).to eq(Split::Algorithms::Whiplash)
end
experiment = Split::Experiment.new('basket_text', :alternatives => ['Basket', "Cart"], :resettable => false)
expect(experiment.resettable).to be_falsey
end
end
describe 'persistent configuration' do
describe "persistent configuration" do
it "should persist resettable in redis" do
experiment = Split::Experiment.new("basket_text", alternatives: ["Basket", "Cart"], resettable: false)
experiment.save
e = Split::ExperimentCatalog.find("basket_text")
expect(e).to eq(experiment)
expect(e.resettable).to be_falsey
end
describe "#metadata" do
let(:experiment) { Split::Experiment.new("basket_text", alternatives: ["Basket", "Cart"], algorithm: Split::Algorithms::Whiplash, metadata: meta) }
let(:meta) { { a: "b" } }
before do
experiment.save
end
it "should delete the key when metadata is removed" do
experiment.metadata = nil
experiment.save
expect(Split.redis.exists?(experiment.metadata_key)).to be_falsey
end
context "simple hash" do
let(:meta) { { "basket" => "a", "cart" => "b" } }
it "should persist metadata in redis" do
e = Split::ExperimentCatalog.find("basket_text")
expect(e).to eq(experiment)
expect(e.metadata).to eq(meta)
end
end
context "nested hash" do
let(:meta) { { "basket" => { "one" => "two" }, "cart" => "b" } }
it "should persist metadata in redis" do
e = Split::ExperimentCatalog.find("basket_text")
expect(e).to eq(experiment)
expect(e.metadata).to eq(meta)
end
end
end
it "should persist algorithm in redis" do
experiment = Split::Experiment.new("basket_text", alternatives: ["Basket", "Cart"], algorithm: Split::Algorithms::Whiplash)
experiment.save
e = Split::ExperimentCatalog.find("basket_text")
expect(e).to eq(experiment)
expect(e.algorithm).to eq(Split::Algorithms::Whiplash)
end
it "should persist a new experiment in redis, that does not exist in the configuration file" do
experiment = Split::Experiment.new("foobar", alternatives: ["tra", "la"], algorithm: Split::Algorithms::Whiplash)
experiment.save
e = Split::ExperimentCatalog.find("foobar")
expect(e).to eq(experiment)
expect(e.alternatives.collect { |a| a.name }).to eq(["tra", "la"])
end
end
describe "deleting" do
it "should delete itself" do
experiment = Split::Experiment.new("basket_text", alternatives: [ "Basket", "Cart"])
experiment.save
experiment.delete
expect(Split.redis.exists?("link_color")).to be false
expect(Split::ExperimentCatalog.find("link_color")).to be_nil
end
it "should increment the version" do
expect(experiment.version).to eq(0)
experiment.delete
expect(experiment.version).to eq(1)
end
it "should call the on_experiment_delete hook" do
expect(Split.configuration.on_experiment_delete).to receive(:call)
experiment.delete
end
it "should call the on_before_experiment_delete hook" do
expect(Split.configuration.on_before_experiment_delete).to receive(:call)
experiment.delete
end
it "should reset the start time if the experiment should be manually started" do
Split.configuration.start_manually = true
experiment.start
experiment.delete
expect(experiment.start_time).to be_nil
end
it "should default cohorting back to false" do
experiment.disable_cohorting
expect(experiment.cohorting_disabled?).to eq(true)
experiment.delete
expect(experiment.cohorting_disabled?).to eq(false)
end
end
describe "winner" do
it "should have no winner initially" do
expect(experiment.winner).to be_nil
end
end
describe "winner=" do
it "should allow you to specify a winner" do
experiment.save
experiment.winner = "red"
expect(experiment.winner.name).to eq("red")
end
it "should call the on_experiment_winner_choose hook" do
expect(Split.configuration.on_experiment_winner_choose).to receive(:call)
experiment.winner = "green"
end
context "when has_winner state is memoized" do
before { expect(experiment).to_not have_winner }
it "should keep has_winner state consistent" do
experiment.winner = "red"
expect(experiment).to have_winner
end
end
end
describe "reset_winner" do
before { experiment.winner = "green" }
it "should reset the winner" do
experiment.reset_winner
expect(experiment.winner).to be_nil
end
context "when has_winner state is memoized" do
before { expect(experiment).to have_winner }
it "should keep has_winner state consistent" do
experiment.reset_winner
expect(experiment).to_not have_winner
end
end
end
describe "has_winner?" do
context "with winner" do
before { experiment.winner = "red" }
it "returns true" do
expect(experiment).to have_winner
end
end
context "without winner" do
it "returns false" do
expect(experiment).to_not have_winner
end
end
it "memoizes has_winner state" do
expect(experiment).to receive(:winner).once
expect(experiment).to_not have_winner
expect(experiment).to_not have_winner
end
end
describe "reset" do
let(:reset_manually) { false }
before do
allow(Split.configuration).to receive(:reset_manually).and_return(reset_manually)
experiment.save
green.increment_participation
green.increment_participation
end
it "should reset all alternatives" do
experiment.winner = "green"
expect(experiment.next_alternative.name).to eq("green")
green.increment_participation
experiment.reset
expect(green.participant_count).to eq(0)
expect(green.completed_count).to eq(0)
end
it "should reset the winner" do
experiment.winner = "green"
expect(experiment.next_alternative.name).to eq("green")
green.increment_participation
experiment.reset
expect(experiment.winner).to be_nil
end
it "should increment the version" do
expect(experiment.version).to eq(0)
experiment.reset
expect(experiment.version).to eq(1)
end
it "should call the on_experiment_reset hook" do
expect(Split.configuration.on_experiment_reset).to receive(:call)
experiment.reset
end
it "should call the on_before_experiment_reset hook" do
expect(Split.configuration.on_before_experiment_reset).to receive(:call)
experiment.reset
end
end
describe "algorithm" do
let(:experiment) { Split::ExperimentCatalog.find_or_create("link_color", "blue", "red", "green") }
it "should use the default algorithm if none is specified" do
expect(experiment.algorithm).to eq(Split.configuration.algorithm)
end
it "should use the user specified algorithm for this experiment if specified" do
experiment.algorithm = Split::Algorithms::Whiplash
expect(experiment.algorithm).to eq(Split::Algorithms::Whiplash)
end
end
describe "#next_alternative" do
context "with multiple alternatives" do
let(:experiment) { Split::ExperimentCatalog.find_or_create("link_color", "blue", "red", "green") }
context "with winner" do
it "should always return the winner" do
green = Split::Alternative.new("green", "link_color")
experiment.winner = "green"
expect(experiment.next_alternative.name).to eq("green")
green.increment_participation
expect(experiment.next_alternative.name).to eq("green")
end
end
context "without winner" do
it "should use the specified algorithm" do
experiment.algorithm = Split::Algorithms::Whiplash
expect(experiment.algorithm).to receive(:choose_alternative).and_return(Split::Alternative.new("green", "link_color"))
expect(experiment.next_alternative.name).to eq("green")
end
end
end
context "with single alternative" do
let(:experiment) { Split::ExperimentCatalog.find_or_create("link_color", "blue") }
it "should always return the only alternative" do
expect(experiment.next_alternative.name).to eq("blue")
expect(experiment.next_alternative.name).to eq("blue")
end
end
end
describe "#cohorting_disabled?" do
it "returns false when nothing has been configured" do
expect(experiment.cohorting_disabled?).to eq false
end
it "returns true when enable_cohorting is performed" do
experiment.enable_cohorting
expect(experiment.cohorting_disabled?).to eq false
end
it "returns false when nothing has been configured" do
experiment.disable_cohorting
expect(experiment.cohorting_disabled?).to eq true
end
end
describe "changing an existing experiment" do
def same_but_different_alternative
Split::ExperimentCatalog.find_or_create("link_color", "blue", "yellow", "orange")
end
it "should reset an experiment if it is loaded with different alternatives" do
experiment.save
blue.participant_count = 5
same_experiment = same_but_different_alternative
expect(same_experiment.alternatives.map(&:name)).to eq(["blue", "yellow", "orange"])
expect(blue.participant_count).to eq(0)
end
it "should only reset once" do
experiment.save
expect(experiment.version).to eq(0)
same_experiment = same_but_different_alternative
expect(same_experiment.version).to eq(1)
same_experiment_again = same_but_different_alternative
expect(same_experiment_again.version).to eq(1)
end
context "when metadata is changed" do
it "should increase version" do
experiment.save
experiment.metadata = { "foo" => "bar" }
expect { experiment.save }.to change { experiment.version }.by(1)
end
it "does not increase version" do
experiment.metadata = nil
experiment.save
expect { experiment.save }.to change { experiment.version }.by(0)
end
end
context "when experiment configuration is changed" do
let(:reset_manually) { false }
before do
experiment.save
allow(Split.configuration).to receive(:reset_manually).and_return(reset_manually)
green.increment_participation
green.increment_participation
experiment.set_alternatives_and_options(alternatives: %w(blue red green zip),
goals: %w(purchase))
experiment.save
end
it "resets all alternatives" do
expect(green.participant_count).to eq(0)
expect(green.completed_count).to eq(0)
end
context "when reset_manually is set" do
let(:reset_manually) { true }
it "does not reset alternatives" do
expect(green.participant_count).to eq(2)
expect(green.completed_count).to eq(0)
end
end
end
end
describe "alternatives passed as non-strings" do
it "should throw an exception if an alternative is passed that is not a string" do
expect { Split::ExperimentCatalog.find_or_create("link_color", :blue, :red) }.to raise_error(ArgumentError)
expect { Split::ExperimentCatalog.find_or_create("link_enabled", true, false) }.to raise_error(ArgumentError)
end
end
describe "specifying weights" do
let(:experiment_with_weight) {
Split::ExperimentCatalog.find_or_create("link_color", { "blue" => 1 }, { "red" => 2 })
}
it "should work for a new experiment" do
expect(experiment_with_weight.alternatives.map(&:weight)).to eq([1, 2])
end
it "should work for an existing experiment" do
experiment.save
expect(experiment_with_weight.alternatives.map(&:weight)).to eq([1, 2])
end
end
describe "specifying goals" do
let(:experiment) {
new_experiment(["purchase"])
}
context "saving experiment" do
let(:same_but_different_goals) { Split::ExperimentCatalog.find_or_create({ "link_color" => ["purchase", "refund"] }, "blue", "red", "green") }
before { experiment.save }
it "can find existing experiment" do
expect(Split::ExperimentCatalog.find("link_color").name).to eq("link_color")
end
it "should reset an experiment if it is loaded with different goals" do
same_but_different_goals
expect(Split::ExperimentCatalog.find("link_color").goals).to eq(["purchase", "refund"])
end
end
it "should have goals" do
expect(experiment.goals).to eq(["purchase"])
end
context "find or create experiment" do
it "should have correct goals" do
experiment = Split::ExperimentCatalog.find_or_create({ "link_color3" => ["purchase", "refund"] }, "blue", "red", "green")
expect(experiment.goals).to eq(["purchase", "refund"])
experiment = Split::ExperimentCatalog.find_or_create("link_color3", "blue", "red", "green")
expect(experiment.goals).to eq([])
end
end
end
describe "beta probability calculation" do
it "should return a hash with the probability of each alternative being the best" do
experiment = Split::ExperimentCatalog.find_or_create("mathematicians", "bernoulli", "poisson", "lagrange")
experiment.calc_winning_alternatives
expect(experiment.alternative_probabilities).not_to be_nil
end
it "should return between 46% and 54% probability for an experiment with 2 alternatives and no data" do
experiment = Split::ExperimentCatalog.find_or_create("scientists", "einstein", "bohr")
experiment.calc_winning_alternatives
expect(experiment.alternatives[0].p_winner).to be_within(0.04).of(0.50)
end
it "should calculate the probability of being the winning alternative separately for each goal", skip: true do
experiment = Split::ExperimentCatalog.find_or_create({ "link_color3" => ["purchase", "refund"] }, "blue", "red", "green")
goal1 = experiment.goals[0]
goal2 = experiment.goals[1]
experiment.alternatives.each do |alternative|
alternative.participant_count = 50
alternative.set_completed_count(10, goal1)
alternative.set_completed_count(15+rand(30), goal2)
end
experiment.calc_winning_alternatives
alt = experiment.alternatives[0]
p_goal1 = alt.p_winner(goal1)
p_goal2 = alt.p_winner(goal2)
expect(p_goal1).not_to be_within(0.04).of(p_goal2)
end
it "should return nil and not re-calculate probabilities if they have already been calculated today" do
experiment = Split::ExperimentCatalog.find_or_create({ "link_color3" => ["purchase", "refund"] }, "blue", "red", "green")
expect(experiment.calc_winning_alternatives).not_to be nil
expect(experiment.calc_winning_alternatives).to be nil
end
end
end
<MSG> Merge pull request #599 from mattwd7/bug-default-experiment-resettable-when-loaded-from-configuration
Respect experiment defaults when loading experiments in initializer.
<DFF> @@ -118,6 +118,23 @@ describe Split::Experiment do
experiment = Split::Experiment.new('basket_text', :alternatives => ['Basket', "Cart"], :resettable => false)
expect(experiment.resettable).to be_falsey
end
+
+ context 'from configuration' do
+ let(:experiment_name) { :my_experiment }
+ let(:experiments) do
+ {
+ experiment_name => {
+ :alternatives => ['Control Opt', 'Alt one']
+ }
+ }
+ end
+
+ before { Split.configuration.experiments = experiments }
+
+ it 'assigns default values to the experiment' do
+ expect(Split::Experiment.new(experiment_name).resettable).to eq(true)
+ end
+ end
end
describe 'persistent configuration' do
| 17 | Merge pull request #599 from mattwd7/bug-default-experiment-resettable-when-loaded-from-configuration | 0 | .rb | rb | mit | splitrb/split |
10071877 | <NME> experiment_spec.rb
<BEF> # frozen_string_literal: true
require "spec_helper"
require "time"
describe Split::Experiment do
def new_experiment(goals = [])
Split::Experiment.new("link_color", alternatives: ["blue", "red", "green"], goals: goals)
end
def alternative(color)
Split::Alternative.new(color, "link_color")
end
let(:experiment) { new_experiment }
let(:blue) { alternative("blue") }
let(:green) { alternative("green") }
context "with an experiment" do
let(:experiment) { Split::Experiment.new("basket_text", alternatives: ["Basket", "Cart"]) }
it "should have a name" do
expect(experiment.name).to eq("basket_text")
end
it "should have alternatives" do
expect(experiment.alternatives.length).to be 2
end
it "should have alternatives with correct names" do
expect(experiment.alternatives.collect { |a| a.name }).to eq(["Basket", "Cart"])
end
it "should be resettable by default" do
expect(experiment.resettable).to be_truthy
end
it "should save to redis" do
experiment.save
expect(Split.redis.exists?("basket_text")).to be true
end
it "should save the start time to redis" do
experiment_start_time = Time.at(1372167761)
expect(Time).to receive(:now).and_return(experiment_start_time)
experiment.save
expect(Split::ExperimentCatalog.find("basket_text").start_time).to eq(experiment_start_time)
end
it "should not save the start time to redis when start_manually is enabled" do
expect(Split.configuration).to receive(:start_manually).and_return(true)
experiment.save
expect(Split::ExperimentCatalog.find("basket_text").start_time).to be_nil
end
it "should save the selected algorithm to redis" do
experiment_algorithm = Split::Algorithms::Whiplash
experiment.algorithm = experiment_algorithm
experiment.save
expect(Split::ExperimentCatalog.find("basket_text").algorithm).to eq(experiment_algorithm)
end
it "should handle having a start time stored as a string" do
experiment_start_time = Time.parse("Sat Mar 03 14:01:03")
expect(Time).to receive(:now).twice.and_return(experiment_start_time)
experiment.save
Split.redis.hset(:experiment_start_times, experiment.name, experiment_start_time.to_s)
expect(Split::ExperimentCatalog.find("basket_text").start_time).to eq(experiment_start_time)
end
it "should handle not having a start time" do
experiment_start_time = Time.parse("Sat Mar 03 14:01:03")
expect(Time).to receive(:now).and_return(experiment_start_time)
experiment.save
Split.redis.hdel(:experiment_start_times, experiment.name)
expect(Split::ExperimentCatalog.find("basket_text").start_time).to be_nil
end
it "should not create duplicates when saving multiple times" do
experiment.save
experiment.save
expect(Split.redis.exists?("basket_text")).to be true
expect(Split.redis.lrange("basket_text", 0, -1)).to eq(['{"Basket":1}', '{"Cart":1}'])
end
describe "new record?" do
it "should know if it hasn't been saved yet" do
expect(experiment.new_record?).to be_truthy
end
it "should know if it has been saved yet" do
experiment.save
expect(experiment.new_record?).to be_falsey
end
end
describe "control" do
it "should be the first alternative" do
experiment.save
expect(experiment.control.name).to eq("Basket")
end
end
end
describe "initialization" do
it "should set the algorithm when passed as an option to the initializer" do
experiment = Split::Experiment.new("basket_text", alternatives: ["Basket", "Cart"], algorithm: Split::Algorithms::Whiplash)
expect(experiment.algorithm).to eq(Split::Algorithms::Whiplash)
end
experiment = Split::Experiment.new('basket_text', :alternatives => ['Basket', "Cart"], :resettable => false)
expect(experiment.resettable).to be_falsey
end
end
describe 'persistent configuration' do
describe "persistent configuration" do
it "should persist resettable in redis" do
experiment = Split::Experiment.new("basket_text", alternatives: ["Basket", "Cart"], resettable: false)
experiment.save
e = Split::ExperimentCatalog.find("basket_text")
expect(e).to eq(experiment)
expect(e.resettable).to be_falsey
end
describe "#metadata" do
let(:experiment) { Split::Experiment.new("basket_text", alternatives: ["Basket", "Cart"], algorithm: Split::Algorithms::Whiplash, metadata: meta) }
let(:meta) { { a: "b" } }
before do
experiment.save
end
it "should delete the key when metadata is removed" do
experiment.metadata = nil
experiment.save
expect(Split.redis.exists?(experiment.metadata_key)).to be_falsey
end
context "simple hash" do
let(:meta) { { "basket" => "a", "cart" => "b" } }
it "should persist metadata in redis" do
e = Split::ExperimentCatalog.find("basket_text")
expect(e).to eq(experiment)
expect(e.metadata).to eq(meta)
end
end
context "nested hash" do
let(:meta) { { "basket" => { "one" => "two" }, "cart" => "b" } }
it "should persist metadata in redis" do
e = Split::ExperimentCatalog.find("basket_text")
expect(e).to eq(experiment)
expect(e.metadata).to eq(meta)
end
end
end
it "should persist algorithm in redis" do
experiment = Split::Experiment.new("basket_text", alternatives: ["Basket", "Cart"], algorithm: Split::Algorithms::Whiplash)
experiment.save
e = Split::ExperimentCatalog.find("basket_text")
expect(e).to eq(experiment)
expect(e.algorithm).to eq(Split::Algorithms::Whiplash)
end
it "should persist a new experiment in redis, that does not exist in the configuration file" do
experiment = Split::Experiment.new("foobar", alternatives: ["tra", "la"], algorithm: Split::Algorithms::Whiplash)
experiment.save
e = Split::ExperimentCatalog.find("foobar")
expect(e).to eq(experiment)
expect(e.alternatives.collect { |a| a.name }).to eq(["tra", "la"])
end
end
describe "deleting" do
it "should delete itself" do
experiment = Split::Experiment.new("basket_text", alternatives: [ "Basket", "Cart"])
experiment.save
experiment.delete
expect(Split.redis.exists?("link_color")).to be false
expect(Split::ExperimentCatalog.find("link_color")).to be_nil
end
it "should increment the version" do
expect(experiment.version).to eq(0)
experiment.delete
expect(experiment.version).to eq(1)
end
it "should call the on_experiment_delete hook" do
expect(Split.configuration.on_experiment_delete).to receive(:call)
experiment.delete
end
it "should call the on_before_experiment_delete hook" do
expect(Split.configuration.on_before_experiment_delete).to receive(:call)
experiment.delete
end
it "should reset the start time if the experiment should be manually started" do
Split.configuration.start_manually = true
experiment.start
experiment.delete
expect(experiment.start_time).to be_nil
end
it "should default cohorting back to false" do
experiment.disable_cohorting
expect(experiment.cohorting_disabled?).to eq(true)
experiment.delete
expect(experiment.cohorting_disabled?).to eq(false)
end
end
describe "winner" do
it "should have no winner initially" do
expect(experiment.winner).to be_nil
end
end
describe "winner=" do
it "should allow you to specify a winner" do
experiment.save
experiment.winner = "red"
expect(experiment.winner.name).to eq("red")
end
it "should call the on_experiment_winner_choose hook" do
expect(Split.configuration.on_experiment_winner_choose).to receive(:call)
experiment.winner = "green"
end
context "when has_winner state is memoized" do
before { expect(experiment).to_not have_winner }
it "should keep has_winner state consistent" do
experiment.winner = "red"
expect(experiment).to have_winner
end
end
end
describe "reset_winner" do
before { experiment.winner = "green" }
it "should reset the winner" do
experiment.reset_winner
expect(experiment.winner).to be_nil
end
context "when has_winner state is memoized" do
before { expect(experiment).to have_winner }
it "should keep has_winner state consistent" do
experiment.reset_winner
expect(experiment).to_not have_winner
end
end
end
describe "has_winner?" do
context "with winner" do
before { experiment.winner = "red" }
it "returns true" do
expect(experiment).to have_winner
end
end
context "without winner" do
it "returns false" do
expect(experiment).to_not have_winner
end
end
it "memoizes has_winner state" do
expect(experiment).to receive(:winner).once
expect(experiment).to_not have_winner
expect(experiment).to_not have_winner
end
end
describe "reset" do
let(:reset_manually) { false }
before do
allow(Split.configuration).to receive(:reset_manually).and_return(reset_manually)
experiment.save
green.increment_participation
green.increment_participation
end
it "should reset all alternatives" do
experiment.winner = "green"
expect(experiment.next_alternative.name).to eq("green")
green.increment_participation
experiment.reset
expect(green.participant_count).to eq(0)
expect(green.completed_count).to eq(0)
end
it "should reset the winner" do
experiment.winner = "green"
expect(experiment.next_alternative.name).to eq("green")
green.increment_participation
experiment.reset
expect(experiment.winner).to be_nil
end
it "should increment the version" do
expect(experiment.version).to eq(0)
experiment.reset
expect(experiment.version).to eq(1)
end
it "should call the on_experiment_reset hook" do
expect(Split.configuration.on_experiment_reset).to receive(:call)
experiment.reset
end
it "should call the on_before_experiment_reset hook" do
expect(Split.configuration.on_before_experiment_reset).to receive(:call)
experiment.reset
end
end
describe "algorithm" do
let(:experiment) { Split::ExperimentCatalog.find_or_create("link_color", "blue", "red", "green") }
it "should use the default algorithm if none is specified" do
expect(experiment.algorithm).to eq(Split.configuration.algorithm)
end
it "should use the user specified algorithm for this experiment if specified" do
experiment.algorithm = Split::Algorithms::Whiplash
expect(experiment.algorithm).to eq(Split::Algorithms::Whiplash)
end
end
describe "#next_alternative" do
context "with multiple alternatives" do
let(:experiment) { Split::ExperimentCatalog.find_or_create("link_color", "blue", "red", "green") }
context "with winner" do
it "should always return the winner" do
green = Split::Alternative.new("green", "link_color")
experiment.winner = "green"
expect(experiment.next_alternative.name).to eq("green")
green.increment_participation
expect(experiment.next_alternative.name).to eq("green")
end
end
context "without winner" do
it "should use the specified algorithm" do
experiment.algorithm = Split::Algorithms::Whiplash
expect(experiment.algorithm).to receive(:choose_alternative).and_return(Split::Alternative.new("green", "link_color"))
expect(experiment.next_alternative.name).to eq("green")
end
end
end
context "with single alternative" do
let(:experiment) { Split::ExperimentCatalog.find_or_create("link_color", "blue") }
it "should always return the only alternative" do
expect(experiment.next_alternative.name).to eq("blue")
expect(experiment.next_alternative.name).to eq("blue")
end
end
end
describe "#cohorting_disabled?" do
it "returns false when nothing has been configured" do
expect(experiment.cohorting_disabled?).to eq false
end
it "returns true when enable_cohorting is performed" do
experiment.enable_cohorting
expect(experiment.cohorting_disabled?).to eq false
end
it "returns false when nothing has been configured" do
experiment.disable_cohorting
expect(experiment.cohorting_disabled?).to eq true
end
end
describe "changing an existing experiment" do
def same_but_different_alternative
Split::ExperimentCatalog.find_or_create("link_color", "blue", "yellow", "orange")
end
it "should reset an experiment if it is loaded with different alternatives" do
experiment.save
blue.participant_count = 5
same_experiment = same_but_different_alternative
expect(same_experiment.alternatives.map(&:name)).to eq(["blue", "yellow", "orange"])
expect(blue.participant_count).to eq(0)
end
it "should only reset once" do
experiment.save
expect(experiment.version).to eq(0)
same_experiment = same_but_different_alternative
expect(same_experiment.version).to eq(1)
same_experiment_again = same_but_different_alternative
expect(same_experiment_again.version).to eq(1)
end
context "when metadata is changed" do
it "should increase version" do
experiment.save
experiment.metadata = { "foo" => "bar" }
expect { experiment.save }.to change { experiment.version }.by(1)
end
it "does not increase version" do
experiment.metadata = nil
experiment.save
expect { experiment.save }.to change { experiment.version }.by(0)
end
end
context "when experiment configuration is changed" do
let(:reset_manually) { false }
before do
experiment.save
allow(Split.configuration).to receive(:reset_manually).and_return(reset_manually)
green.increment_participation
green.increment_participation
experiment.set_alternatives_and_options(alternatives: %w(blue red green zip),
goals: %w(purchase))
experiment.save
end
it "resets all alternatives" do
expect(green.participant_count).to eq(0)
expect(green.completed_count).to eq(0)
end
context "when reset_manually is set" do
let(:reset_manually) { true }
it "does not reset alternatives" do
expect(green.participant_count).to eq(2)
expect(green.completed_count).to eq(0)
end
end
end
end
describe "alternatives passed as non-strings" do
it "should throw an exception if an alternative is passed that is not a string" do
expect { Split::ExperimentCatalog.find_or_create("link_color", :blue, :red) }.to raise_error(ArgumentError)
expect { Split::ExperimentCatalog.find_or_create("link_enabled", true, false) }.to raise_error(ArgumentError)
end
end
describe "specifying weights" do
let(:experiment_with_weight) {
Split::ExperimentCatalog.find_or_create("link_color", { "blue" => 1 }, { "red" => 2 })
}
it "should work for a new experiment" do
expect(experiment_with_weight.alternatives.map(&:weight)).to eq([1, 2])
end
it "should work for an existing experiment" do
experiment.save
expect(experiment_with_weight.alternatives.map(&:weight)).to eq([1, 2])
end
end
describe "specifying goals" do
let(:experiment) {
new_experiment(["purchase"])
}
context "saving experiment" do
let(:same_but_different_goals) { Split::ExperimentCatalog.find_or_create({ "link_color" => ["purchase", "refund"] }, "blue", "red", "green") }
before { experiment.save }
it "can find existing experiment" do
expect(Split::ExperimentCatalog.find("link_color").name).to eq("link_color")
end
it "should reset an experiment if it is loaded with different goals" do
same_but_different_goals
expect(Split::ExperimentCatalog.find("link_color").goals).to eq(["purchase", "refund"])
end
end
it "should have goals" do
expect(experiment.goals).to eq(["purchase"])
end
context "find or create experiment" do
it "should have correct goals" do
experiment = Split::ExperimentCatalog.find_or_create({ "link_color3" => ["purchase", "refund"] }, "blue", "red", "green")
expect(experiment.goals).to eq(["purchase", "refund"])
experiment = Split::ExperimentCatalog.find_or_create("link_color3", "blue", "red", "green")
expect(experiment.goals).to eq([])
end
end
end
describe "beta probability calculation" do
it "should return a hash with the probability of each alternative being the best" do
experiment = Split::ExperimentCatalog.find_or_create("mathematicians", "bernoulli", "poisson", "lagrange")
experiment.calc_winning_alternatives
expect(experiment.alternative_probabilities).not_to be_nil
end
it "should return between 46% and 54% probability for an experiment with 2 alternatives and no data" do
experiment = Split::ExperimentCatalog.find_or_create("scientists", "einstein", "bohr")
experiment.calc_winning_alternatives
expect(experiment.alternatives[0].p_winner).to be_within(0.04).of(0.50)
end
it "should calculate the probability of being the winning alternative separately for each goal", skip: true do
experiment = Split::ExperimentCatalog.find_or_create({ "link_color3" => ["purchase", "refund"] }, "blue", "red", "green")
goal1 = experiment.goals[0]
goal2 = experiment.goals[1]
experiment.alternatives.each do |alternative|
alternative.participant_count = 50
alternative.set_completed_count(10, goal1)
alternative.set_completed_count(15+rand(30), goal2)
end
experiment.calc_winning_alternatives
alt = experiment.alternatives[0]
p_goal1 = alt.p_winner(goal1)
p_goal2 = alt.p_winner(goal2)
expect(p_goal1).not_to be_within(0.04).of(p_goal2)
end
it "should return nil and not re-calculate probabilities if they have already been calculated today" do
experiment = Split::ExperimentCatalog.find_or_create({ "link_color3" => ["purchase", "refund"] }, "blue", "red", "green")
expect(experiment.calc_winning_alternatives).not_to be nil
expect(experiment.calc_winning_alternatives).to be nil
end
end
end
<MSG> Merge pull request #599 from mattwd7/bug-default-experiment-resettable-when-loaded-from-configuration
Respect experiment defaults when loading experiments in initializer.
<DFF> @@ -118,6 +118,23 @@ describe Split::Experiment do
experiment = Split::Experiment.new('basket_text', :alternatives => ['Basket', "Cart"], :resettable => false)
expect(experiment.resettable).to be_falsey
end
+
+ context 'from configuration' do
+ let(:experiment_name) { :my_experiment }
+ let(:experiments) do
+ {
+ experiment_name => {
+ :alternatives => ['Control Opt', 'Alt one']
+ }
+ }
+ end
+
+ before { Split.configuration.experiments = experiments }
+
+ it 'assigns default values to the experiment' do
+ expect(Split::Experiment.new(experiment_name).resettable).to eq(true)
+ end
+ end
end
describe 'persistent configuration' do
| 17 | Merge pull request #599 from mattwd7/bug-default-experiment-resettable-when-loaded-from-configuration | 0 | .rb | rb | mit | splitrb/split |
10071878 | <NME> helper_spec.rb
<BEF> # frozen_string_literal: true
require "spec_helper"
# TODO change some of these tests to use Rack::Test
describe Split::Helper do
include Split::Helper
let(:experiment) {
Split::ExperimentCatalog.find_or_create("link_color", "blue", "red")
}
describe "ab_test" do
it "should not raise an error when passed strings for alternatives" do
expect { ab_test("xyz", "1", "2", "3") }.not_to raise_error
end
it "should not raise an error when passed an array for alternatives" do
expect { ab_test("xyz", ["1", "2", "3"]) }.not_to raise_error
end
it "should raise the appropriate error when passed integers for alternatives" do
expect { ab_test("xyz", 1, 2, 3) }.to raise_error(ArgumentError)
end
it "should raise the appropriate error when passed symbols for alternatives" do
expect { ab_test("xyz", :a, :b, :c) }.to raise_error(ArgumentError)
end
it "should not raise error when passed an array for goals" do
expect { ab_test({ "link_color" => ["purchase", "refund"] }, "blue", "red") }.not_to raise_error
end
it "should not raise error when passed just one goal" do
expect { ab_test({ "link_color" => "purchase" }, "blue", "red") }.not_to raise_error
end
it "raises an appropriate error when processing combined expirements" do
Split.configuration.experiments = {
combined_exp_1: {
alternatives: [ { name: "control", percent: 50 }, { name: "test-alt", percent: 50 } ],
metric: :my_metric,
combined_experiments: [:combined_exp_1_sub_1]
}
}
Split::ExperimentCatalog.find_or_create("combined_exp_1")
expect { ab_test("combined_exp_1") }.to raise_error(Split::InvalidExperimentsFormatError)
end
it "should assign a random alternative to a new user when there are an equal number of alternatives assigned" do
ab_test("link_color", "blue", "red")
expect(["red", "blue"]).to include(ab_user["link_color"])
end
it "should increment the participation counter after assignment to a new user" do
previous_red_count = Split::Alternative.new("red", "link_color").participant_count
previous_blue_count = Split::Alternative.new("blue", "link_color").participant_count
ab_test("link_color", "blue", "red")
new_red_count = Split::Alternative.new("red", "link_color").participant_count
new_blue_count = Split::Alternative.new("blue", "link_color").participant_count
expect((new_red_count + new_blue_count)).to eq(previous_red_count + previous_blue_count + 1)
end
it "should not increment the counter for an experiment that the user is not participating in" do
ab_test("link_color", "blue", "red")
e = Split::ExperimentCatalog.find_or_create("button_size", "small", "big")
expect {
# User shouldn't participate in this second experiment
ab_test("button_size", "small", "big")
}.not_to change { e.participant_count }
end
it "should not increment the counter for an ended experiment" do
e = Split::ExperimentCatalog.find_or_create("button_size", "small", "big")
e.winner = "small"
expect {
a = ab_test("button_size", "small", "big")
expect(a).to eq("small")
}.not_to change { e.participant_count }
end
it "should not increment the counter for an not started experiment" do
expect(Split.configuration).to receive(:start_manually).and_return(true)
e = Split::ExperimentCatalog.find_or_create("button_size", "small", "big")
expect {
a = ab_test("button_size", "small", "big")
expect(a).to eq("small")
}.not_to change { e.participant_count }
end
it "should return the given alternative for an existing user" do
expect(ab_test("link_color", "blue", "red")).to eq ab_test("link_color", "blue", "red")
end
it "should always return the winner if one is present" do
experiment.winner = "orange"
expect(ab_test("link_color", "blue", "red")).to eq("orange")
end
it "should allow the alternative to be forced by passing it in the params" do
# ?ab_test[link_color]=blue
@params = { "ab_test" => { "link_color" => "blue" } }
alternative = ab_test("link_color", "blue", "red")
expect(alternative).to eq("blue")
alternative = ab_test("link_color", { "blue" => 1 }, "red" => 5)
expect(alternative).to eq("blue")
@params = { "ab_test" => { "link_color" => "red" } }
alternative = ab_test("link_color", "blue", "red")
expect(alternative).to eq("red")
alternative = ab_test("link_color", { "blue" => 5 }, "red" => 1)
expect(alternative).to eq("red")
end
it "should not allow an arbitrary alternative" do
@params = { "ab_test" => { "link_color" => "pink" } }
alternative = ab_test("link_color", "blue")
expect(alternative).to eq("blue")
end
it "should not store the split when a param forced alternative" do
@params = { "ab_test" => { "link_color" => "blue" } }
expect(ab_user).not_to receive(:[]=)
ab_test("link_color", "blue", "red")
end
it "SPLIT_DISABLE query parameter should also force the alternative (uses control)" do
@params = { "SPLIT_DISABLE" => "true" }
alternative = ab_test("link_color", "blue", "red")
expect(alternative).to eq("blue")
alternative = ab_test("link_color", { "blue" => 1 }, "red" => 5)
expect(alternative).to eq("blue")
alternative = ab_test("link_color", "red", "blue")
expect(alternative).to eq("red")
alternative = ab_test("link_color", { "red" => 5 }, "blue" => 1)
expect(alternative).to eq("red")
end
it "should not store the split when Split generically disabled" do
@params = { "SPLIT_DISABLE" => "true" }
expect(ab_user).not_to receive(:[]=)
ab_test("link_color", "blue", "red")
end
context "when store_override is set" do
before { Split.configuration.store_override = true }
it "should store the forced alternative" do
@params = { "ab_test" => { "link_color" => "blue" } }
expect(ab_user).to receive(:[]=).with("link_color", "blue")
ab_test("link_color", "blue", "red")
end
end
context "when on_trial_choose is set" do
before { Split.configuration.on_trial_choose = :some_method }
it "should call the method" do
expect(self).to receive(:some_method)
ab_test("link_color", "blue", "red")
end
end
it "should allow passing a block" do
alt = ab_test("link_color", "blue", "red")
ret = ab_test("link_color", "blue", "red") { |alternative| "shared/#{alternative}" }
expect(ret).to eq("shared/#{alt}")
end
it "should allow the share of visitors see an alternative to be specified" do
ab_test("link_color", { "blue" => 0.8 }, { "red" => 20 })
expect(["red", "blue"]).to include(ab_user["link_color"])
end
it "should allow alternative weighting interface as a single hash" do
ab_test("link_color", { "blue" => 0.01 }, "red" => 0.2)
experiment = Split::ExperimentCatalog.find("link_color")
expect(experiment.alternatives.map(&:name)).to eq(["blue", "red"])
expect(experiment.alternatives.collect { |a| a.weight }).to match_array([0.01, 0.2])
end
it "should only let a user participate in one experiment at a time" do
link_color = ab_test("link_color", "blue", "red")
ab_test("button_size", "small", "big")
expect(ab_user["link_color"]).to eq(link_color)
big = Split::Alternative.new("big", "button_size")
expect(big.participant_count).to eq(0)
small = Split::Alternative.new("small", "button_size")
expect(small.participant_count).to eq(0)
end
it "should let a user participate in many experiment with allow_multiple_experiments option" do
Split.configure do |config|
config.allow_multiple_experiments = true
end
link_color = ab_test("link_color", "blue", "red")
button_size = ab_test("button_size", "small", "big")
expect(ab_user["link_color"]).to eq(link_color)
expect(ab_user["button_size"]).to eq(button_size)
button_size_alt = Split::Alternative.new(button_size, "button_size")
expect(button_size_alt.participant_count).to eq(1)
end
context "with allow_multiple_experiments = 'control'" do
it "should let a user participate in many experiment with one non-'control' alternative" do
Split.configure do |config|
config.allow_multiple_experiments = "control"
end
groups = 100.times.map do |n|
ab_test("test#{n}".to_sym, { "control" => (100 - n) }, { "test#{n}-alt" => n })
end
experiments = ab_user.active_experiments
expect(experiments.size).to be > 1
count_control = experiments.values.count { |g| g == "control" }
expect(count_control).to eq(experiments.size - 1)
count_alts = groups.count { |g| g != "control" }
expect(count_alts).to eq(1)
end
context "when user already has experiment" do
let(:mock_user) { Split::User.new(self, { "test_0" => "test-alt" }) }
before do
Split.configure do |config|
config.allow_multiple_experiments = "control"
end
Split::ExperimentCatalog.find_or_initialize("test_0", "control", "test-alt").save
Split::ExperimentCatalog.find_or_initialize("test_1", "control", "test-alt").save
end
it "should restore previously selected alternative" do
expect(ab_user.active_experiments.size).to eq 1
expect(ab_test(:test_0, { "control" => 100 }, { "test-alt" => 1 })).to eq "test-alt"
expect(ab_test(:test_0, { "control" => 1 }, { "test-alt" => 100 })).to eq "test-alt"
end
it "should select the correct alternatives after experiment resets" do
experiment = Split::ExperimentCatalog.find(:test_0)
experiment.reset
mock_user[experiment.key] = "test-alt"
expect(ab_user.active_experiments.size).to eq 1
expect(ab_test(:test_0, { "control" => 100 }, { "test-alt" => 1 })).to eq "test-alt"
expect(ab_test(:test_0, { "control" => 0 }, { "test-alt" => 100 })).to eq "test-alt"
end
it "lets override existing choice" do
pending "this requires user store reset on first call not depending on whelther it is current trial"
@params = { "ab_test" => { "test_1" => "test-alt" } }
expect(ab_test(:test_0, { "control" => 0 }, { "test-alt" => 100 })).to eq "control"
expect(ab_test(:test_1, { "control" => 100 }, { "test-alt" => 1 })).to eq "test-alt"
end
end
end
it "should not over-write a finished key when an experiment is on a later version" do
experiment.increment_version
ab_user = { experiment.key => "blue", experiment.finished_key => true }
finished_session = ab_user.dup
ab_test("link_color", "blue", "red")
expect(ab_user).to eq(finished_session)
end
end
describe "metadata" do
context "is defined" do
before do
Split.configuration.experiments = {
my_experiment: {
alternatives: ["one", "two"],
resettable: false,
metadata: { "one" => "Meta1", "two" => "Meta2" }
}
}
end
it "should be passed to helper block" do
@params = { "ab_test" => { "my_experiment" => "two" } }
expect(ab_test("my_experiment")).to eq "two"
expect(ab_test("my_experiment") do |alternative, meta|
meta
end).to eq("Meta2")
end
it "should pass control metadata helper block if library disabled" do
Split.configure do |config|
config.enabled = false
end
expect(ab_test("my_experiment")).to eq "one"
expect(ab_test("my_experiment") do |_, meta|
meta
end).to eq("Meta1")
end
end
context "is not defined" do
before do
Split.configuration.experiments = {
my_experiment: {
alternatives: ["one", "two"],
resettable: false,
metadata: nil
}
}
end
it "should be passed to helper block" do
expect(ab_test("my_experiment") do |alternative, meta|
meta
end).to eq({})
end
it "should pass control metadata helper block if library disabled" do
Split.configure do |config|
config.enabled = false
end
expect(ab_test("my_experiment") do |_, meta|
meta
end).to eq({})
end
end
end
describe "ab_finished" do
context "for an experiment that the user participates in" do
before(:each) do
@experiment_name = "link_color"
@alternatives = ["blue", "red"]
@experiment = Split::ExperimentCatalog.find_or_create(@experiment_name, *@alternatives)
@alternative_name = ab_test(@experiment_name, *@alternatives)
@previous_completion_count = Split::Alternative.new(@alternative_name, @experiment_name).completed_count
end
it "should increment the counter for the completed alternative" do
ab_finished(@experiment_name)
new_completion_count = Split::Alternative.new(@alternative_name, @experiment_name).completed_count
expect(new_completion_count).to eq(@previous_completion_count + 1)
end
it "should set experiment's finished key if reset is false" do
ab_finished(@experiment_name, { reset: false })
expect(ab_user[@experiment.key]).to eq(@alternative_name)
expect(ab_user[@experiment.finished_key]).to eq(true)
end
it "should not increment the counter if reset is false and the experiment has been already finished" do
2.times { ab_finished(@experiment_name, { reset: false }) }
new_completion_count = Split::Alternative.new(@alternative_name, @experiment_name).completed_count
expect(new_completion_count).to eq(@previous_completion_count + 1)
end
it "should not increment the counter for an ended experiment" do
e = Split::ExperimentCatalog.find_or_create("button_size", "small", "big")
e.winner = "small"
a = ab_test("button_size", "small", "big")
expect(a).to eq("small")
expect {
ab_finished("button_size")
}.not_to change { Split::Alternative.new(a, "button_size").completed_count }
end
it "should clear out the user's participation from their session" do
expect(ab_user[@experiment.key]).to eq(@alternative_name)
ab_finished(@experiment_name)
expect(ab_user.keys).to be_empty
end
it "should not clear out the users session if reset is false" do
expect(ab_user[@experiment.key]).to eq(@alternative_name)
ab_finished(@experiment_name, { reset: false })
expect(ab_user[@experiment.key]).to eq(@alternative_name)
expect(ab_user[@experiment.finished_key]).to eq(true)
end
it "should reset the users session when experiment is not versioned" do
expect(ab_user[@experiment.key]).to eq(@alternative_name)
ab_finished(@experiment_name)
expect(ab_user.keys).to be_empty
end
it "should reset the users session when experiment is versioned" do
@experiment.increment_version
@alternative_name = ab_test(@experiment_name, *@alternatives)
expect(ab_user[@experiment.key]).to eq(@alternative_name)
ab_finished(@experiment_name)
expect(ab_user.keys).to be_empty
end
context "when on_trial_complete is set" do
before { Split.configuration.on_trial_complete = :some_method }
it "should call the method" do
expect(self).to receive(:some_method)
ab_finished(@experiment_name)
end
it "should not call the method without alternative" do
ab_user[@experiment.key] = nil
expect(self).not_to receive(:some_method)
ab_finished(@experiment_name)
end
end
end
context "for an experiment that the user is excluded from" do
before do
alternative = ab_test("link_color", "blue", "red")
expect(Split::Alternative.new(alternative, "link_color").participant_count).to eq(1)
alternative = ab_test("button_size", "small", "big")
expect(Split::Alternative.new(alternative, "button_size").participant_count).to eq(0)
end
it "should not increment the completed counter" do
# So, user should be participating in the link_color experiment and
# receive the control for button_size. As the user is not participating in
# the button size experiment, finishing it should not increase the
# completion count for that alternative.
expect {
ab_finished("button_size")
}.not_to change { Split::Alternative.new("small", "button_size").completed_count }
end
end
context "for an experiment that the user does not participate in" do
before do
Split::ExperimentCatalog.find_or_create(:not_started_experiment, "control", "alt")
end
it "should not raise an exception" do
expect { ab_finished(:not_started_experiment) }.not_to raise_exception
end
it "should not change the user state when reset is false" do
expect { ab_finished(:not_started_experiment, reset: false) }.not_to change { ab_user.keys }.from([])
end
it "should not change the user state when reset is true" do
expect(self).not_to receive(:reset!)
ab_finished(:not_started_experiment)
end
it "should not increment the completed counter" do
ab_finished(:not_started_experiment)
expect(Split::Alternative.new("control", :not_started_experiment).completed_count).to eq(0)
expect(Split::Alternative.new("alt", :not_started_experiment).completed_count).to eq(0)
end
end
end
context "finished with config" do
it "passes reset option" do
Split.configuration.experiments = {
my_experiment: {
alternatives: ["one", "two"],
resettable: false,
}
}
alternative = ab_test(:my_experiment)
experiment = Split::ExperimentCatalog.find :my_experiment
ab_finished :my_experiment
expect(ab_user[experiment.key]).to eq(alternative)
expect(ab_user[experiment.finished_key]).to eq(true)
end
end
context "finished with metric name" do
before { Split.configuration.experiments = {} }
before { expect(Split::Alternative).to receive(:new).at_least(1).times.and_call_original }
def should_finish_experiment(experiment_name, should_finish = true)
alts = Split.configuration.experiments[experiment_name][:alternatives]
experiment = Split::ExperimentCatalog.find_or_create(experiment_name, *alts)
alt_name = ab_user[experiment.key] = alts.first
alt = double("alternative")
expect(alt).to receive(:name).at_most(1).times.and_return(alt_name)
expect(Split::Alternative).to receive(:new).at_most(1).times.with(alt_name, experiment_name.to_s).and_return(alt)
if should_finish
expect(alt).to receive(:increment_completion).at_most(1).times
else
expect(alt).not_to receive(:increment_completion)
end
end
it "completes the test" do
Split.configuration.experiments[:my_experiment] = {
alternatives: [ "control_opt", "other_opt" ],
metric: :my_metric
}
should_finish_experiment :my_experiment
ab_finished :my_metric
end
it "completes all relevant tests" do
Split.configuration.experiments = {
exp_1: {
alternatives: [ "1-1", "1-2" ],
metric: :my_metric
},
exp_2: {
alternatives: [ "2-1", "2-2" ],
metric: :another_metric
},
exp_3: {
alternatives: [ "3-1", "3-2" ],
metric: :my_metric
},
}
should_finish_experiment :exp_1
should_finish_experiment :exp_2, false
should_finish_experiment :exp_3
ab_finished :my_metric
end
it "passes reset option" do
Split.configuration.experiments = {
my_exp: {
alternatives: ["one", "two"],
metric: :my_metric,
resettable: false,
}
}
alternative_name = ab_test(:my_exp)
exp = Split::ExperimentCatalog.find :my_exp
ab_finished :my_metric
expect(ab_user[exp.key]).to eq(alternative_name)
expect(ab_user[exp.finished_key]).to be_truthy
end
it "passes through options" do
Split.configuration.experiments = {
my_exp: {
alternatives: ["one", "two"],
metric: :my_metric,
}
}
alternative_name = ab_test(:my_exp)
exp = Split::ExperimentCatalog.find :my_exp
ab_finished :my_metric, reset: false
expect(ab_user[exp.key]).to eq(alternative_name)
expect(ab_user[exp.finished_key]).to be_truthy
end
end
describe "conversions" do
it "should return a conversion rate for an alternative" do
alternative_name = ab_test("link_color", "blue", "red")
previous_convertion_rate = Split::Alternative.new(alternative_name, "link_color").conversion_rate
expect(previous_convertion_rate).to eq(0.0)
ab_finished("link_color")
new_convertion_rate = Split::Alternative.new(alternative_name, "link_color").conversion_rate
expect(new_convertion_rate).to eq(1.0)
end
end
describe "active experiments" do
it "should show an active test" do
alternative = ab_test("def", "4", "5", "6")
expect(active_experiments.count).to eq 1
expect(active_experiments.first[0]).to eq "def"
expect(active_experiments.first[1]).to eq alternative
end
it "should show a finished test" do
alternative = ab_test("def", "4", "5", "6")
ab_finished("def", { reset: false })
expect(active_experiments.count).to eq 1
expect(active_experiments.first[0]).to eq "def"
expect(active_experiments.first[1]).to eq alternative
end
it "should show an active test when an experiment is on a later version" do
experiment.reset
expect(experiment.version).to eq(1)
ab_test("link_color", "blue", "red")
expect(active_experiments.count).to eq 1
expect(active_experiments.first[0]).to eq "link_color"
it "accepts multiple goals" do
Split.configuration.experiments[:my_experiment] = {
:variants => [ "control_opt", "other_opt" ],
:goals => [ "goal1", "goal2", "goal3" ]
}
ab_test :my_experiment
expect(experiment.version).to eq(10)
expect(active_experiments.count).to eq 1
it "allow specifying goals to be optional" do
Split.configuration.experiments[:my_experiment] = {
:variants => [ "control_opt", "other_opt" ]
}
experiment = Split::Experiment.find(:my_experiment)
experiment.goals.should == []
alternative = ab_test("def", "4", "5", "6")
another_alternative = ab_test("ghi", "7", "8", "9")
expect(active_experiments.count).to eq 2
expect(active_experiments["def"]).to eq alternative
expect(active_experiments["ghi"]).to eq another_alternative
end
it "should not show tests with winners" do
Split.configure do |config|
config.allow_multiple_experiments = true
end
e = Split::ExperimentCatalog.find_or_create("def", "4", "5", "6")
e.winner = "4"
ab_test("def", "4", "5", "6")
another_alternative = ab_test("ghi", "7", "8", "9")
expect(active_experiments.count).to eq 1
expect(active_experiments.first[0]).to eq "ghi"
expect(active_experiments.first[1]).to eq another_alternative
end
end
describe "when user is a robot" do
before(:each) do
@request = OpenStruct.new(user_agent: "Googlebot/2.1 (+http://www.google.com/bot.html)")
end
describe "ab_test" do
it "should return the control" do
alternative = ab_test("link_color", "blue", "red")
expect(alternative).to eq experiment.control.name
end
it "should not create a experiment" do
ab_test("link_color", "blue", "red")
expect(Split::Experiment.new("link_color")).to be_a_new_record
end
it "should not increment the participation count" do
previous_red_count = Split::Alternative.new("red", "link_color").participant_count
previous_blue_count = Split::Alternative.new("blue", "link_color").participant_count
ab_test("link_color", "blue", "red")
new_red_count = Split::Alternative.new("red", "link_color").participant_count
new_blue_count = Split::Alternative.new("blue", "link_color").participant_count
expect((new_red_count + new_blue_count)).to eq(previous_red_count + previous_blue_count)
end
end
describe "finished" do
it "should not increment the completed count" do
alternative_name = ab_test("link_color", "blue", "red")
previous_completion_count = Split::Alternative.new(alternative_name, "link_color").completed_count
ab_finished("link_color")
new_completion_count = Split::Alternative.new(alternative_name, "link_color").completed_count
expect(new_completion_count).to eq(previous_completion_count)
end
end
end
describe "when providing custom ignore logic" do
context "using a proc to configure custom logic" do
before(:each) do
Split.configure do |c|
c.ignore_filter = proc { |request| true } # ignore everything
end
end
it "ignores the ab_test" do
ab_test("link_color", "blue", "red")
red_count = Split::Alternative.new("red", "link_color").participant_count
blue_count = Split::Alternative.new("blue", "link_color").participant_count
expect((red_count + blue_count)).to be(0)
end
end
end
shared_examples_for "a disabled test" do
describe "ab_test" do
it "should return the control" do
alternative = ab_test("link_color", "blue", "red")
expect(alternative).to eq experiment.control.name
end
it "should not increment the participation count" do
previous_red_count = Split::Alternative.new("red", "link_color").participant_count
previous_blue_count = Split::Alternative.new("blue", "link_color").participant_count
ab_test("link_color", "blue", "red")
new_red_count = Split::Alternative.new("red", "link_color").participant_count
new_blue_count = Split::Alternative.new("blue", "link_color").participant_count
expect((new_red_count + new_blue_count)).to eq(previous_red_count + previous_blue_count)
end
end
describe "finished" do
it "should not increment the completed count" do
alternative_name = ab_test("link_color", "blue", "red")
previous_completion_count = Split::Alternative.new(alternative_name, "link_color").completed_count
ab_finished("link_color")
new_completion_count = Split::Alternative.new(alternative_name, "link_color").completed_count
expect(new_completion_count).to eq(previous_completion_count)
end
end
end
describe "when ip address is ignored" do
context "individually" do
before(:each) do
@request = OpenStruct.new(ip: "81.19.48.130")
Split.configure do |c|
c.ignore_ip_addresses << "81.19.48.130"
end
end
it_behaves_like "a disabled test"
end
context "for a range" do
before(:each) do
@request = OpenStruct.new(ip: "81.19.48.129")
Split.configure do |c|
c.ignore_ip_addresses << /81\.19\.48\.[0-9]+/
end
end
it_behaves_like "a disabled test"
end
context "using both a range and a specific value" do
before(:each) do
@request = OpenStruct.new(ip: "81.19.48.128")
Split.configure do |c|
c.ignore_ip_addresses << "81.19.48.130"
c.ignore_ip_addresses << /81\.19\.48\.[0-9]+/
end
end
it_behaves_like "a disabled test"
end
context "when ignored other address" do
before do
@request = OpenStruct.new(ip: "1.1.1.1")
Split.configure do |c|
c.ignore_ip_addresses << "81.19.48.130"
end
end
it "works as usual" do
alternative_name = ab_test("link_color", "red", "blue")
expect {
ab_finished("link_color")
}.to change(Split::Alternative.new(alternative_name, "link_color"), :completed_count).by(1)
end
end
end
describe "when user is previewing" do
before(:each) do
@request = OpenStruct.new(headers: { "x-purpose" => "preview" })
end
it_behaves_like "a disabled test"
end
describe "versioned experiments" do
it "should use version zero if no version is present" do
alternative_name = ab_test("link_color", "blue", "red")
expect(experiment.version).to eq(0)
expect(ab_user["link_color"]).to eq(alternative_name)
end
it "should save the version of the experiment to the session" do
experiment.reset
expect(experiment.version).to eq(1)
alternative_name = ab_test("link_color", "blue", "red")
expect(ab_user["link_color:1"]).to eq(alternative_name)
end
it "should load the experiment even if the version is not 0" do
experiment.reset
expect(experiment.version).to eq(1)
alternative_name = ab_test("link_color", "blue", "red")
expect(ab_user["link_color:1"]).to eq(alternative_name)
return_alternative_name = ab_test("link_color", "blue", "red")
expect(return_alternative_name).to eq(alternative_name)
end
it "should reset the session of a user on an older version of the experiment" do
alternative_name = ab_test("link_color", "blue", "red")
expect(ab_user["link_color"]).to eq(alternative_name)
alternative = Split::Alternative.new(alternative_name, "link_color")
expect(alternative.participant_count).to eq(1)
experiment.reset
expect(experiment.version).to eq(1)
alternative = Split::Alternative.new(alternative_name, "link_color")
expect(alternative.participant_count).to eq(0)
new_alternative_name = ab_test("link_color", "blue", "red")
expect(ab_user["link_color:1"]).to eq(new_alternative_name)
new_alternative = Split::Alternative.new(new_alternative_name, "link_color")
expect(new_alternative.participant_count).to eq(1)
end
it "should cleanup old versions of experiments from the session" do
alternative_name = ab_test("link_color", "blue", "red")
expect(ab_user["link_color"]).to eq(alternative_name)
alternative = Split::Alternative.new(alternative_name, "link_color")
expect(alternative.participant_count).to eq(1)
experiment.reset
expect(experiment.version).to eq(1)
alternative = Split::Alternative.new(alternative_name, "link_color")
expect(alternative.participant_count).to eq(0)
new_alternative_name = ab_test("link_color", "blue", "red")
expect(ab_user["link_color:1"]).to eq(new_alternative_name)
end
it "should only count completion of users on the current version" do
alternative_name = ab_test("link_color", "blue", "red")
expect(ab_user["link_color"]).to eq(alternative_name)
Split::Alternative.new(alternative_name, "link_color")
experiment.reset
expect(experiment.version).to eq(1)
ab_finished("link_color")
alternative = Split::Alternative.new(alternative_name, "link_color")
expect(alternative.completed_count).to eq(0)
end
end
context "when redis is not available" do
before(:each) do
expect(Split).to receive(:redis).at_most(5).times.and_raise(Errno::ECONNREFUSED.new)
end
context "and db_failover config option is turned off" do
before(:each) do
Split.configure do |config|
config.db_failover = false
end
end
describe "ab_test" do
it "should raise an exception" do
expect { ab_test("link_color", "blue", "red") }.to raise_error(Errno::ECONNREFUSED)
end
end
describe "finished" do
it "should raise an exception" do
expect { ab_finished("link_color") }.to raise_error(Errno::ECONNREFUSED)
end
end
describe "disable split testing" do
before(:each) do
Split.configure do |config|
config.enabled = false
end
end
it "should not attempt to connect to redis" do
expect { ab_test("link_color", "blue", "red") }.not_to raise_error
end
it "should return control variable" do
expect(ab_test("link_color", "blue", "red")).to eq("blue")
expect { ab_finished("link_color") }.not_to raise_error
end
end
end
context "and db_failover config option is turned on" do
before(:each) do
Split.configure do |config|
config.db_failover = true
end
end
describe "ab_test" do
it "should not raise an exception" do
expect { ab_test("link_color", "blue", "red") }.not_to raise_error
end
it "should call db_failover_on_db_error proc with error as parameter" do
Split.configure do |config|
config.db_failover_on_db_error = proc do |error|
expect(error).to be_a(Errno::ECONNREFUSED)
end
end
expect(Split.configuration.db_failover_on_db_error).to receive(:call).and_call_original
ab_test("link_color", "blue", "red")
end
it "should always use first alternative" do
expect(ab_test("link_color", "blue", "red")).to eq("blue")
expect(ab_test("link_color", { "blue" => 0.01 }, "red" => 0.2)).to eq("blue")
expect(ab_test("link_color", { "blue" => 0.8 }, { "red" => 20 })).to eq("blue")
expect(ab_test("link_color", "blue", "red") do |alternative|
"shared/#{alternative}"
end).to eq("shared/blue")
end
context "and db_failover_allow_parameter_override config option is turned on" do
before(:each) do
Split.configure do |config|
config.db_failover_allow_parameter_override = true
end
end
context "and given an override parameter" do
it "should use given override instead of the first alternative" do
@params = { "ab_test" => { "link_color" => "red" } }
expect(ab_test("link_color", "blue", "red")).to eq("red")
expect(ab_test("link_color", "blue", "red", "green")).to eq("red")
expect(ab_test("link_color", { "blue" => 0.01 }, "red" => 0.2)).to eq("red")
expect(ab_test("link_color", { "blue" => 0.8 }, { "red" => 20 })).to eq("red")
expect(ab_test("link_color", "blue", "red") do |alternative|
"shared/#{alternative}"
end).to eq("shared/red")
end
end
end
context "and preloaded config given" do
before do
Split.configuration.experiments[:link_color] = {
alternatives: [ "blue", "red" ],
}
end
it "uses first alternative" do
expect(ab_test(:link_color)).to eq("blue")
end
end
end
describe "finished" do
it "should not raise an exception" do
expect { ab_finished("link_color") }.not_to raise_error
end
it "should call db_failover_on_db_error proc with error as parameter" do
Split.configure do |config|
config.db_failover_on_db_error = proc do |error|
expect(error).to be_a(Errno::ECONNREFUSED)
end
end
expect(Split.configuration.db_failover_on_db_error).to receive(:call).and_call_original
ab_finished("link_color")
end
end
end
end
context "with preloaded config" do
before { Split.configuration.experiments = {} }
it "pulls options from config file" do
Split.configuration.experiments[:my_experiment] = {
alternatives: [ "control_opt", "other_opt" ],
goals: ["goal1", "goal2"]
}
ab_test :my_experiment
expect(Split::Experiment.new(:my_experiment).alternatives.map(&:name)).to eq([ "control_opt", "other_opt" ])
expect(Split::Experiment.new(:my_experiment).goals).to eq([ "goal1", "goal2" ])
end
it "can be called multiple times" do
Split.configuration.experiments[:my_experiment] = {
alternatives: [ "control_opt", "other_opt" ],
goals: ["goal1", "goal2"]
}
5.times { ab_test :my_experiment }
experiment = Split::Experiment.new(:my_experiment)
expect(experiment.alternatives.map(&:name)).to eq([ "control_opt", "other_opt" ])
expect(experiment.goals).to eq([ "goal1", "goal2" ])
expect(experiment.participant_count).to eq(1)
end
it "accepts multiple goals" do
Split.configuration.experiments[:my_experiment] = {
alternatives: [ "control_opt", "other_opt" ],
goals: [ "goal1", "goal2", "goal3" ]
}
ab_test :my_experiment
experiment = Split::Experiment.new(:my_experiment)
expect(experiment.goals).to eq([ "goal1", "goal2", "goal3" ])
end
it "allow specifying goals to be optional" do
Split.configuration.experiments[:my_experiment] = {
alternatives: [ "control_opt", "other_opt" ]
}
experiment = Split::Experiment.new(:my_experiment)
expect(experiment.goals).to eq([])
end
it "accepts multiple alternatives" do
Split.configuration.experiments[:my_experiment] = {
alternatives: [ "control_opt", "second_opt", "third_opt" ],
}
ab_test :my_experiment
experiment = Split::Experiment.new(:my_experiment)
expect(experiment.alternatives.map(&:name)).to eq([ "control_opt", "second_opt", "third_opt" ])
end
it "accepts probability on alternatives" do
Split.configuration.experiments[:my_experiment] = {
alternatives: [
{ name: "control_opt", percent: 67 },
{ name: "second_opt", percent: 10 },
{ name: "third_opt", percent: 23 },
],
}
ab_test :my_experiment
experiment = Split::Experiment.new(:my_experiment)
expect(experiment.alternatives.collect { |a| [a.name, a.weight] }).to eq([["control_opt", 0.67], ["second_opt", 0.1], ["third_opt", 0.23]])
end
it "accepts probability on some alternatives" do
Split.configuration.experiments[:my_experiment] = {
alternatives: [
{ name: "control_opt", percent: 34 },
"second_opt",
{ name: "third_opt", percent: 23 },
"fourth_opt",
],
}
ab_test :my_experiment
experiment = Split::Experiment.new(:my_experiment)
names_and_weights = experiment.alternatives.collect { |a| [a.name, a.weight] }
expect(names_and_weights).to eq([["control_opt", 0.34], ["second_opt", 0.215], ["third_opt", 0.23], ["fourth_opt", 0.215]])
expect(names_and_weights.inject(0) { |sum, nw| sum + nw[1] }).to eq(1.0)
end
it "allows name param without probability" do
Split.configuration.experiments[:my_experiment] = {
alternatives: [
{ name: "control_opt" },
"second_opt",
{ name: "third_opt", percent: 64 },
],
}
ab_test :my_experiment
experiment = Split::Experiment.new(:my_experiment)
names_and_weights = experiment.alternatives.collect { |a| [a.name, a.weight] }
expect(names_and_weights).to eq([["control_opt", 0.18], ["second_opt", 0.18], ["third_opt", 0.64]])
expect(names_and_weights.inject(0) { |sum, nw| sum + nw[1] }).to eq(1.0)
end
it "fails gracefully if config is missing experiment" do
Split.configuration.experiments = { other_experiment: { foo: "Bar" } }
expect { ab_test :my_experiment }.to raise_error(Split::ExperimentNotFound)
end
it "fails gracefully if config is missing" do
expect { Split.configuration.experiments = nil }.to raise_error(Split::InvalidExperimentsFormatError)
end
it "fails gracefully if config is missing alternatives" do
Split.configuration.experiments[:my_experiment] = { foo: "Bar" }
expect { ab_test :my_experiment }.to raise_error(NoMethodError)
end
end
it "should handle multiple experiments correctly" do
experiment2 = Split::ExperimentCatalog.find_or_create("link_color2", "blue", "red")
ab_test("link_color", "blue", "red")
ab_test("link_color2", "blue", "red")
ab_finished("link_color2")
experiment2.alternatives.each do |alt|
expect(alt.unfinished_count).to eq(0)
end
end
context "with goals" do
before do
@experiment = { "link_color" => ["purchase", "refund"] }
@alternatives = ["blue", "red"]
@experiment_name, @goals = normalize_metric(@experiment)
@goal1 = @goals[0]
@goal2 = @goals[1]
end
it "should normalize experiment" do
expect(@experiment_name).to eq("link_color")
expect(@goals).to eq(["purchase", "refund"])
end
describe "ab_test" do
it "should allow experiment goals interface as a single hash" do
ab_test(@experiment, *@alternatives)
experiment = Split::ExperimentCatalog.find("link_color")
expect(experiment.goals).to eq(["purchase", "refund"])
end
end
describe "ab_finished" do
before do
@alternative_name = ab_test(@experiment, *@alternatives)
end
it "should increment the counter for the specified-goal completed alternative" do
expect { ab_finished({ "link_color" => ["purchase"] }) }
.to change { Split::Alternative.new(@alternative_name, @experiment_name).completed_count(@goal2) }.by(0)
.and change { Split::Alternative.new(@alternative_name, @experiment_name).completed_count(@goal1) }.by(1)
end
end
end
end
<MSG> rename variants to alternatives
<DFF> @@ -597,7 +597,7 @@ describe Split::Helper do
it "accepts multiple goals" do
Split.configuration.experiments[:my_experiment] = {
- :variants => [ "control_opt", "other_opt" ],
+ :alternatives => [ "control_opt", "other_opt" ],
:goals => [ "goal1", "goal2", "goal3" ]
}
ab_test :my_experiment
@@ -607,7 +607,7 @@ describe Split::Helper do
it "allow specifying goals to be optional" do
Split.configuration.experiments[:my_experiment] = {
- :variants => [ "control_opt", "other_opt" ]
+ :alternatives => [ "control_opt", "other_opt" ]
}
experiment = Split::Experiment.find(:my_experiment)
experiment.goals.should == []
| 2 | rename variants to alternatives | 2 | .rb | rb | mit | splitrb/split |
10071879 | <NME> helper_spec.rb
<BEF> # frozen_string_literal: true
require "spec_helper"
# TODO change some of these tests to use Rack::Test
describe Split::Helper do
include Split::Helper
let(:experiment) {
Split::ExperimentCatalog.find_or_create("link_color", "blue", "red")
}
describe "ab_test" do
it "should not raise an error when passed strings for alternatives" do
expect { ab_test("xyz", "1", "2", "3") }.not_to raise_error
end
it "should not raise an error when passed an array for alternatives" do
expect { ab_test("xyz", ["1", "2", "3"]) }.not_to raise_error
end
it "should raise the appropriate error when passed integers for alternatives" do
expect { ab_test("xyz", 1, 2, 3) }.to raise_error(ArgumentError)
end
it "should raise the appropriate error when passed symbols for alternatives" do
expect { ab_test("xyz", :a, :b, :c) }.to raise_error(ArgumentError)
end
it "should not raise error when passed an array for goals" do
expect { ab_test({ "link_color" => ["purchase", "refund"] }, "blue", "red") }.not_to raise_error
end
it "should not raise error when passed just one goal" do
expect { ab_test({ "link_color" => "purchase" }, "blue", "red") }.not_to raise_error
end
it "raises an appropriate error when processing combined expirements" do
Split.configuration.experiments = {
combined_exp_1: {
alternatives: [ { name: "control", percent: 50 }, { name: "test-alt", percent: 50 } ],
metric: :my_metric,
combined_experiments: [:combined_exp_1_sub_1]
}
}
Split::ExperimentCatalog.find_or_create("combined_exp_1")
expect { ab_test("combined_exp_1") }.to raise_error(Split::InvalidExperimentsFormatError)
end
it "should assign a random alternative to a new user when there are an equal number of alternatives assigned" do
ab_test("link_color", "blue", "red")
expect(["red", "blue"]).to include(ab_user["link_color"])
end
it "should increment the participation counter after assignment to a new user" do
previous_red_count = Split::Alternative.new("red", "link_color").participant_count
previous_blue_count = Split::Alternative.new("blue", "link_color").participant_count
ab_test("link_color", "blue", "red")
new_red_count = Split::Alternative.new("red", "link_color").participant_count
new_blue_count = Split::Alternative.new("blue", "link_color").participant_count
expect((new_red_count + new_blue_count)).to eq(previous_red_count + previous_blue_count + 1)
end
it "should not increment the counter for an experiment that the user is not participating in" do
ab_test("link_color", "blue", "red")
e = Split::ExperimentCatalog.find_or_create("button_size", "small", "big")
expect {
# User shouldn't participate in this second experiment
ab_test("button_size", "small", "big")
}.not_to change { e.participant_count }
end
it "should not increment the counter for an ended experiment" do
e = Split::ExperimentCatalog.find_or_create("button_size", "small", "big")
e.winner = "small"
expect {
a = ab_test("button_size", "small", "big")
expect(a).to eq("small")
}.not_to change { e.participant_count }
end
it "should not increment the counter for an not started experiment" do
expect(Split.configuration).to receive(:start_manually).and_return(true)
e = Split::ExperimentCatalog.find_or_create("button_size", "small", "big")
expect {
a = ab_test("button_size", "small", "big")
expect(a).to eq("small")
}.not_to change { e.participant_count }
end
it "should return the given alternative for an existing user" do
expect(ab_test("link_color", "blue", "red")).to eq ab_test("link_color", "blue", "red")
end
it "should always return the winner if one is present" do
experiment.winner = "orange"
expect(ab_test("link_color", "blue", "red")).to eq("orange")
end
it "should allow the alternative to be forced by passing it in the params" do
# ?ab_test[link_color]=blue
@params = { "ab_test" => { "link_color" => "blue" } }
alternative = ab_test("link_color", "blue", "red")
expect(alternative).to eq("blue")
alternative = ab_test("link_color", { "blue" => 1 }, "red" => 5)
expect(alternative).to eq("blue")
@params = { "ab_test" => { "link_color" => "red" } }
alternative = ab_test("link_color", "blue", "red")
expect(alternative).to eq("red")
alternative = ab_test("link_color", { "blue" => 5 }, "red" => 1)
expect(alternative).to eq("red")
end
it "should not allow an arbitrary alternative" do
@params = { "ab_test" => { "link_color" => "pink" } }
alternative = ab_test("link_color", "blue")
expect(alternative).to eq("blue")
end
it "should not store the split when a param forced alternative" do
@params = { "ab_test" => { "link_color" => "blue" } }
expect(ab_user).not_to receive(:[]=)
ab_test("link_color", "blue", "red")
end
it "SPLIT_DISABLE query parameter should also force the alternative (uses control)" do
@params = { "SPLIT_DISABLE" => "true" }
alternative = ab_test("link_color", "blue", "red")
expect(alternative).to eq("blue")
alternative = ab_test("link_color", { "blue" => 1 }, "red" => 5)
expect(alternative).to eq("blue")
alternative = ab_test("link_color", "red", "blue")
expect(alternative).to eq("red")
alternative = ab_test("link_color", { "red" => 5 }, "blue" => 1)
expect(alternative).to eq("red")
end
it "should not store the split when Split generically disabled" do
@params = { "SPLIT_DISABLE" => "true" }
expect(ab_user).not_to receive(:[]=)
ab_test("link_color", "blue", "red")
end
context "when store_override is set" do
before { Split.configuration.store_override = true }
it "should store the forced alternative" do
@params = { "ab_test" => { "link_color" => "blue" } }
expect(ab_user).to receive(:[]=).with("link_color", "blue")
ab_test("link_color", "blue", "red")
end
end
context "when on_trial_choose is set" do
before { Split.configuration.on_trial_choose = :some_method }
it "should call the method" do
expect(self).to receive(:some_method)
ab_test("link_color", "blue", "red")
end
end
it "should allow passing a block" do
alt = ab_test("link_color", "blue", "red")
ret = ab_test("link_color", "blue", "red") { |alternative| "shared/#{alternative}" }
expect(ret).to eq("shared/#{alt}")
end
it "should allow the share of visitors see an alternative to be specified" do
ab_test("link_color", { "blue" => 0.8 }, { "red" => 20 })
expect(["red", "blue"]).to include(ab_user["link_color"])
end
it "should allow alternative weighting interface as a single hash" do
ab_test("link_color", { "blue" => 0.01 }, "red" => 0.2)
experiment = Split::ExperimentCatalog.find("link_color")
expect(experiment.alternatives.map(&:name)).to eq(["blue", "red"])
expect(experiment.alternatives.collect { |a| a.weight }).to match_array([0.01, 0.2])
end
it "should only let a user participate in one experiment at a time" do
link_color = ab_test("link_color", "blue", "red")
ab_test("button_size", "small", "big")
expect(ab_user["link_color"]).to eq(link_color)
big = Split::Alternative.new("big", "button_size")
expect(big.participant_count).to eq(0)
small = Split::Alternative.new("small", "button_size")
expect(small.participant_count).to eq(0)
end
it "should let a user participate in many experiment with allow_multiple_experiments option" do
Split.configure do |config|
config.allow_multiple_experiments = true
end
link_color = ab_test("link_color", "blue", "red")
button_size = ab_test("button_size", "small", "big")
expect(ab_user["link_color"]).to eq(link_color)
expect(ab_user["button_size"]).to eq(button_size)
button_size_alt = Split::Alternative.new(button_size, "button_size")
expect(button_size_alt.participant_count).to eq(1)
end
context "with allow_multiple_experiments = 'control'" do
it "should let a user participate in many experiment with one non-'control' alternative" do
Split.configure do |config|
config.allow_multiple_experiments = "control"
end
groups = 100.times.map do |n|
ab_test("test#{n}".to_sym, { "control" => (100 - n) }, { "test#{n}-alt" => n })
end
experiments = ab_user.active_experiments
expect(experiments.size).to be > 1
count_control = experiments.values.count { |g| g == "control" }
expect(count_control).to eq(experiments.size - 1)
count_alts = groups.count { |g| g != "control" }
expect(count_alts).to eq(1)
end
context "when user already has experiment" do
let(:mock_user) { Split::User.new(self, { "test_0" => "test-alt" }) }
before do
Split.configure do |config|
config.allow_multiple_experiments = "control"
end
Split::ExperimentCatalog.find_or_initialize("test_0", "control", "test-alt").save
Split::ExperimentCatalog.find_or_initialize("test_1", "control", "test-alt").save
end
it "should restore previously selected alternative" do
expect(ab_user.active_experiments.size).to eq 1
expect(ab_test(:test_0, { "control" => 100 }, { "test-alt" => 1 })).to eq "test-alt"
expect(ab_test(:test_0, { "control" => 1 }, { "test-alt" => 100 })).to eq "test-alt"
end
it "should select the correct alternatives after experiment resets" do
experiment = Split::ExperimentCatalog.find(:test_0)
experiment.reset
mock_user[experiment.key] = "test-alt"
expect(ab_user.active_experiments.size).to eq 1
expect(ab_test(:test_0, { "control" => 100 }, { "test-alt" => 1 })).to eq "test-alt"
expect(ab_test(:test_0, { "control" => 0 }, { "test-alt" => 100 })).to eq "test-alt"
end
it "lets override existing choice" do
pending "this requires user store reset on first call not depending on whelther it is current trial"
@params = { "ab_test" => { "test_1" => "test-alt" } }
expect(ab_test(:test_0, { "control" => 0 }, { "test-alt" => 100 })).to eq "control"
expect(ab_test(:test_1, { "control" => 100 }, { "test-alt" => 1 })).to eq "test-alt"
end
end
end
it "should not over-write a finished key when an experiment is on a later version" do
experiment.increment_version
ab_user = { experiment.key => "blue", experiment.finished_key => true }
finished_session = ab_user.dup
ab_test("link_color", "blue", "red")
expect(ab_user).to eq(finished_session)
end
end
describe "metadata" do
context "is defined" do
before do
Split.configuration.experiments = {
my_experiment: {
alternatives: ["one", "two"],
resettable: false,
metadata: { "one" => "Meta1", "two" => "Meta2" }
}
}
end
it "should be passed to helper block" do
@params = { "ab_test" => { "my_experiment" => "two" } }
expect(ab_test("my_experiment")).to eq "two"
expect(ab_test("my_experiment") do |alternative, meta|
meta
end).to eq("Meta2")
end
it "should pass control metadata helper block if library disabled" do
Split.configure do |config|
config.enabled = false
end
expect(ab_test("my_experiment")).to eq "one"
expect(ab_test("my_experiment") do |_, meta|
meta
end).to eq("Meta1")
end
end
context "is not defined" do
before do
Split.configuration.experiments = {
my_experiment: {
alternatives: ["one", "two"],
resettable: false,
metadata: nil
}
}
end
it "should be passed to helper block" do
expect(ab_test("my_experiment") do |alternative, meta|
meta
end).to eq({})
end
it "should pass control metadata helper block if library disabled" do
Split.configure do |config|
config.enabled = false
end
expect(ab_test("my_experiment") do |_, meta|
meta
end).to eq({})
end
end
end
describe "ab_finished" do
context "for an experiment that the user participates in" do
before(:each) do
@experiment_name = "link_color"
@alternatives = ["blue", "red"]
@experiment = Split::ExperimentCatalog.find_or_create(@experiment_name, *@alternatives)
@alternative_name = ab_test(@experiment_name, *@alternatives)
@previous_completion_count = Split::Alternative.new(@alternative_name, @experiment_name).completed_count
end
it "should increment the counter for the completed alternative" do
ab_finished(@experiment_name)
new_completion_count = Split::Alternative.new(@alternative_name, @experiment_name).completed_count
expect(new_completion_count).to eq(@previous_completion_count + 1)
end
it "should set experiment's finished key if reset is false" do
ab_finished(@experiment_name, { reset: false })
expect(ab_user[@experiment.key]).to eq(@alternative_name)
expect(ab_user[@experiment.finished_key]).to eq(true)
end
it "should not increment the counter if reset is false and the experiment has been already finished" do
2.times { ab_finished(@experiment_name, { reset: false }) }
new_completion_count = Split::Alternative.new(@alternative_name, @experiment_name).completed_count
expect(new_completion_count).to eq(@previous_completion_count + 1)
end
it "should not increment the counter for an ended experiment" do
e = Split::ExperimentCatalog.find_or_create("button_size", "small", "big")
e.winner = "small"
a = ab_test("button_size", "small", "big")
expect(a).to eq("small")
expect {
ab_finished("button_size")
}.not_to change { Split::Alternative.new(a, "button_size").completed_count }
end
it "should clear out the user's participation from their session" do
expect(ab_user[@experiment.key]).to eq(@alternative_name)
ab_finished(@experiment_name)
expect(ab_user.keys).to be_empty
end
it "should not clear out the users session if reset is false" do
expect(ab_user[@experiment.key]).to eq(@alternative_name)
ab_finished(@experiment_name, { reset: false })
expect(ab_user[@experiment.key]).to eq(@alternative_name)
expect(ab_user[@experiment.finished_key]).to eq(true)
end
it "should reset the users session when experiment is not versioned" do
expect(ab_user[@experiment.key]).to eq(@alternative_name)
ab_finished(@experiment_name)
expect(ab_user.keys).to be_empty
end
it "should reset the users session when experiment is versioned" do
@experiment.increment_version
@alternative_name = ab_test(@experiment_name, *@alternatives)
expect(ab_user[@experiment.key]).to eq(@alternative_name)
ab_finished(@experiment_name)
expect(ab_user.keys).to be_empty
end
context "when on_trial_complete is set" do
before { Split.configuration.on_trial_complete = :some_method }
it "should call the method" do
expect(self).to receive(:some_method)
ab_finished(@experiment_name)
end
it "should not call the method without alternative" do
ab_user[@experiment.key] = nil
expect(self).not_to receive(:some_method)
ab_finished(@experiment_name)
end
end
end
context "for an experiment that the user is excluded from" do
before do
alternative = ab_test("link_color", "blue", "red")
expect(Split::Alternative.new(alternative, "link_color").participant_count).to eq(1)
alternative = ab_test("button_size", "small", "big")
expect(Split::Alternative.new(alternative, "button_size").participant_count).to eq(0)
end
it "should not increment the completed counter" do
# So, user should be participating in the link_color experiment and
# receive the control for button_size. As the user is not participating in
# the button size experiment, finishing it should not increase the
# completion count for that alternative.
expect {
ab_finished("button_size")
}.not_to change { Split::Alternative.new("small", "button_size").completed_count }
end
end
context "for an experiment that the user does not participate in" do
before do
Split::ExperimentCatalog.find_or_create(:not_started_experiment, "control", "alt")
end
it "should not raise an exception" do
expect { ab_finished(:not_started_experiment) }.not_to raise_exception
end
it "should not change the user state when reset is false" do
expect { ab_finished(:not_started_experiment, reset: false) }.not_to change { ab_user.keys }.from([])
end
it "should not change the user state when reset is true" do
expect(self).not_to receive(:reset!)
ab_finished(:not_started_experiment)
end
it "should not increment the completed counter" do
ab_finished(:not_started_experiment)
expect(Split::Alternative.new("control", :not_started_experiment).completed_count).to eq(0)
expect(Split::Alternative.new("alt", :not_started_experiment).completed_count).to eq(0)
end
end
end
context "finished with config" do
it "passes reset option" do
Split.configuration.experiments = {
my_experiment: {
alternatives: ["one", "two"],
resettable: false,
}
}
alternative = ab_test(:my_experiment)
experiment = Split::ExperimentCatalog.find :my_experiment
ab_finished :my_experiment
expect(ab_user[experiment.key]).to eq(alternative)
expect(ab_user[experiment.finished_key]).to eq(true)
end
end
context "finished with metric name" do
before { Split.configuration.experiments = {} }
before { expect(Split::Alternative).to receive(:new).at_least(1).times.and_call_original }
def should_finish_experiment(experiment_name, should_finish = true)
alts = Split.configuration.experiments[experiment_name][:alternatives]
experiment = Split::ExperimentCatalog.find_or_create(experiment_name, *alts)
alt_name = ab_user[experiment.key] = alts.first
alt = double("alternative")
expect(alt).to receive(:name).at_most(1).times.and_return(alt_name)
expect(Split::Alternative).to receive(:new).at_most(1).times.with(alt_name, experiment_name.to_s).and_return(alt)
if should_finish
expect(alt).to receive(:increment_completion).at_most(1).times
else
expect(alt).not_to receive(:increment_completion)
end
end
it "completes the test" do
Split.configuration.experiments[:my_experiment] = {
alternatives: [ "control_opt", "other_opt" ],
metric: :my_metric
}
should_finish_experiment :my_experiment
ab_finished :my_metric
end
it "completes all relevant tests" do
Split.configuration.experiments = {
exp_1: {
alternatives: [ "1-1", "1-2" ],
metric: :my_metric
},
exp_2: {
alternatives: [ "2-1", "2-2" ],
metric: :another_metric
},
exp_3: {
alternatives: [ "3-1", "3-2" ],
metric: :my_metric
},
}
should_finish_experiment :exp_1
should_finish_experiment :exp_2, false
should_finish_experiment :exp_3
ab_finished :my_metric
end
it "passes reset option" do
Split.configuration.experiments = {
my_exp: {
alternatives: ["one", "two"],
metric: :my_metric,
resettable: false,
}
}
alternative_name = ab_test(:my_exp)
exp = Split::ExperimentCatalog.find :my_exp
ab_finished :my_metric
expect(ab_user[exp.key]).to eq(alternative_name)
expect(ab_user[exp.finished_key]).to be_truthy
end
it "passes through options" do
Split.configuration.experiments = {
my_exp: {
alternatives: ["one", "two"],
metric: :my_metric,
}
}
alternative_name = ab_test(:my_exp)
exp = Split::ExperimentCatalog.find :my_exp
ab_finished :my_metric, reset: false
expect(ab_user[exp.key]).to eq(alternative_name)
expect(ab_user[exp.finished_key]).to be_truthy
end
end
describe "conversions" do
it "should return a conversion rate for an alternative" do
alternative_name = ab_test("link_color", "blue", "red")
previous_convertion_rate = Split::Alternative.new(alternative_name, "link_color").conversion_rate
expect(previous_convertion_rate).to eq(0.0)
ab_finished("link_color")
new_convertion_rate = Split::Alternative.new(alternative_name, "link_color").conversion_rate
expect(new_convertion_rate).to eq(1.0)
end
end
describe "active experiments" do
it "should show an active test" do
alternative = ab_test("def", "4", "5", "6")
expect(active_experiments.count).to eq 1
expect(active_experiments.first[0]).to eq "def"
expect(active_experiments.first[1]).to eq alternative
end
it "should show a finished test" do
alternative = ab_test("def", "4", "5", "6")
ab_finished("def", { reset: false })
expect(active_experiments.count).to eq 1
expect(active_experiments.first[0]).to eq "def"
expect(active_experiments.first[1]).to eq alternative
end
it "should show an active test when an experiment is on a later version" do
experiment.reset
expect(experiment.version).to eq(1)
ab_test("link_color", "blue", "red")
expect(active_experiments.count).to eq 1
expect(active_experiments.first[0]).to eq "link_color"
it "accepts multiple goals" do
Split.configuration.experiments[:my_experiment] = {
:variants => [ "control_opt", "other_opt" ],
:goals => [ "goal1", "goal2", "goal3" ]
}
ab_test :my_experiment
expect(experiment.version).to eq(10)
expect(active_experiments.count).to eq 1
it "allow specifying goals to be optional" do
Split.configuration.experiments[:my_experiment] = {
:variants => [ "control_opt", "other_opt" ]
}
experiment = Split::Experiment.find(:my_experiment)
experiment.goals.should == []
alternative = ab_test("def", "4", "5", "6")
another_alternative = ab_test("ghi", "7", "8", "9")
expect(active_experiments.count).to eq 2
expect(active_experiments["def"]).to eq alternative
expect(active_experiments["ghi"]).to eq another_alternative
end
it "should not show tests with winners" do
Split.configure do |config|
config.allow_multiple_experiments = true
end
e = Split::ExperimentCatalog.find_or_create("def", "4", "5", "6")
e.winner = "4"
ab_test("def", "4", "5", "6")
another_alternative = ab_test("ghi", "7", "8", "9")
expect(active_experiments.count).to eq 1
expect(active_experiments.first[0]).to eq "ghi"
expect(active_experiments.first[1]).to eq another_alternative
end
end
describe "when user is a robot" do
before(:each) do
@request = OpenStruct.new(user_agent: "Googlebot/2.1 (+http://www.google.com/bot.html)")
end
describe "ab_test" do
it "should return the control" do
alternative = ab_test("link_color", "blue", "red")
expect(alternative).to eq experiment.control.name
end
it "should not create a experiment" do
ab_test("link_color", "blue", "red")
expect(Split::Experiment.new("link_color")).to be_a_new_record
end
it "should not increment the participation count" do
previous_red_count = Split::Alternative.new("red", "link_color").participant_count
previous_blue_count = Split::Alternative.new("blue", "link_color").participant_count
ab_test("link_color", "blue", "red")
new_red_count = Split::Alternative.new("red", "link_color").participant_count
new_blue_count = Split::Alternative.new("blue", "link_color").participant_count
expect((new_red_count + new_blue_count)).to eq(previous_red_count + previous_blue_count)
end
end
describe "finished" do
it "should not increment the completed count" do
alternative_name = ab_test("link_color", "blue", "red")
previous_completion_count = Split::Alternative.new(alternative_name, "link_color").completed_count
ab_finished("link_color")
new_completion_count = Split::Alternative.new(alternative_name, "link_color").completed_count
expect(new_completion_count).to eq(previous_completion_count)
end
end
end
describe "when providing custom ignore logic" do
context "using a proc to configure custom logic" do
before(:each) do
Split.configure do |c|
c.ignore_filter = proc { |request| true } # ignore everything
end
end
it "ignores the ab_test" do
ab_test("link_color", "blue", "red")
red_count = Split::Alternative.new("red", "link_color").participant_count
blue_count = Split::Alternative.new("blue", "link_color").participant_count
expect((red_count + blue_count)).to be(0)
end
end
end
shared_examples_for "a disabled test" do
describe "ab_test" do
it "should return the control" do
alternative = ab_test("link_color", "blue", "red")
expect(alternative).to eq experiment.control.name
end
it "should not increment the participation count" do
previous_red_count = Split::Alternative.new("red", "link_color").participant_count
previous_blue_count = Split::Alternative.new("blue", "link_color").participant_count
ab_test("link_color", "blue", "red")
new_red_count = Split::Alternative.new("red", "link_color").participant_count
new_blue_count = Split::Alternative.new("blue", "link_color").participant_count
expect((new_red_count + new_blue_count)).to eq(previous_red_count + previous_blue_count)
end
end
describe "finished" do
it "should not increment the completed count" do
alternative_name = ab_test("link_color", "blue", "red")
previous_completion_count = Split::Alternative.new(alternative_name, "link_color").completed_count
ab_finished("link_color")
new_completion_count = Split::Alternative.new(alternative_name, "link_color").completed_count
expect(new_completion_count).to eq(previous_completion_count)
end
end
end
describe "when ip address is ignored" do
context "individually" do
before(:each) do
@request = OpenStruct.new(ip: "81.19.48.130")
Split.configure do |c|
c.ignore_ip_addresses << "81.19.48.130"
end
end
it_behaves_like "a disabled test"
end
context "for a range" do
before(:each) do
@request = OpenStruct.new(ip: "81.19.48.129")
Split.configure do |c|
c.ignore_ip_addresses << /81\.19\.48\.[0-9]+/
end
end
it_behaves_like "a disabled test"
end
context "using both a range and a specific value" do
before(:each) do
@request = OpenStruct.new(ip: "81.19.48.128")
Split.configure do |c|
c.ignore_ip_addresses << "81.19.48.130"
c.ignore_ip_addresses << /81\.19\.48\.[0-9]+/
end
end
it_behaves_like "a disabled test"
end
context "when ignored other address" do
before do
@request = OpenStruct.new(ip: "1.1.1.1")
Split.configure do |c|
c.ignore_ip_addresses << "81.19.48.130"
end
end
it "works as usual" do
alternative_name = ab_test("link_color", "red", "blue")
expect {
ab_finished("link_color")
}.to change(Split::Alternative.new(alternative_name, "link_color"), :completed_count).by(1)
end
end
end
describe "when user is previewing" do
before(:each) do
@request = OpenStruct.new(headers: { "x-purpose" => "preview" })
end
it_behaves_like "a disabled test"
end
describe "versioned experiments" do
it "should use version zero if no version is present" do
alternative_name = ab_test("link_color", "blue", "red")
expect(experiment.version).to eq(0)
expect(ab_user["link_color"]).to eq(alternative_name)
end
it "should save the version of the experiment to the session" do
experiment.reset
expect(experiment.version).to eq(1)
alternative_name = ab_test("link_color", "blue", "red")
expect(ab_user["link_color:1"]).to eq(alternative_name)
end
it "should load the experiment even if the version is not 0" do
experiment.reset
expect(experiment.version).to eq(1)
alternative_name = ab_test("link_color", "blue", "red")
expect(ab_user["link_color:1"]).to eq(alternative_name)
return_alternative_name = ab_test("link_color", "blue", "red")
expect(return_alternative_name).to eq(alternative_name)
end
it "should reset the session of a user on an older version of the experiment" do
alternative_name = ab_test("link_color", "blue", "red")
expect(ab_user["link_color"]).to eq(alternative_name)
alternative = Split::Alternative.new(alternative_name, "link_color")
expect(alternative.participant_count).to eq(1)
experiment.reset
expect(experiment.version).to eq(1)
alternative = Split::Alternative.new(alternative_name, "link_color")
expect(alternative.participant_count).to eq(0)
new_alternative_name = ab_test("link_color", "blue", "red")
expect(ab_user["link_color:1"]).to eq(new_alternative_name)
new_alternative = Split::Alternative.new(new_alternative_name, "link_color")
expect(new_alternative.participant_count).to eq(1)
end
it "should cleanup old versions of experiments from the session" do
alternative_name = ab_test("link_color", "blue", "red")
expect(ab_user["link_color"]).to eq(alternative_name)
alternative = Split::Alternative.new(alternative_name, "link_color")
expect(alternative.participant_count).to eq(1)
experiment.reset
expect(experiment.version).to eq(1)
alternative = Split::Alternative.new(alternative_name, "link_color")
expect(alternative.participant_count).to eq(0)
new_alternative_name = ab_test("link_color", "blue", "red")
expect(ab_user["link_color:1"]).to eq(new_alternative_name)
end
it "should only count completion of users on the current version" do
alternative_name = ab_test("link_color", "blue", "red")
expect(ab_user["link_color"]).to eq(alternative_name)
Split::Alternative.new(alternative_name, "link_color")
experiment.reset
expect(experiment.version).to eq(1)
ab_finished("link_color")
alternative = Split::Alternative.new(alternative_name, "link_color")
expect(alternative.completed_count).to eq(0)
end
end
context "when redis is not available" do
before(:each) do
expect(Split).to receive(:redis).at_most(5).times.and_raise(Errno::ECONNREFUSED.new)
end
context "and db_failover config option is turned off" do
before(:each) do
Split.configure do |config|
config.db_failover = false
end
end
describe "ab_test" do
it "should raise an exception" do
expect { ab_test("link_color", "blue", "red") }.to raise_error(Errno::ECONNREFUSED)
end
end
describe "finished" do
it "should raise an exception" do
expect { ab_finished("link_color") }.to raise_error(Errno::ECONNREFUSED)
end
end
describe "disable split testing" do
before(:each) do
Split.configure do |config|
config.enabled = false
end
end
it "should not attempt to connect to redis" do
expect { ab_test("link_color", "blue", "red") }.not_to raise_error
end
it "should return control variable" do
expect(ab_test("link_color", "blue", "red")).to eq("blue")
expect { ab_finished("link_color") }.not_to raise_error
end
end
end
context "and db_failover config option is turned on" do
before(:each) do
Split.configure do |config|
config.db_failover = true
end
end
describe "ab_test" do
it "should not raise an exception" do
expect { ab_test("link_color", "blue", "red") }.not_to raise_error
end
it "should call db_failover_on_db_error proc with error as parameter" do
Split.configure do |config|
config.db_failover_on_db_error = proc do |error|
expect(error).to be_a(Errno::ECONNREFUSED)
end
end
expect(Split.configuration.db_failover_on_db_error).to receive(:call).and_call_original
ab_test("link_color", "blue", "red")
end
it "should always use first alternative" do
expect(ab_test("link_color", "blue", "red")).to eq("blue")
expect(ab_test("link_color", { "blue" => 0.01 }, "red" => 0.2)).to eq("blue")
expect(ab_test("link_color", { "blue" => 0.8 }, { "red" => 20 })).to eq("blue")
expect(ab_test("link_color", "blue", "red") do |alternative|
"shared/#{alternative}"
end).to eq("shared/blue")
end
context "and db_failover_allow_parameter_override config option is turned on" do
before(:each) do
Split.configure do |config|
config.db_failover_allow_parameter_override = true
end
end
context "and given an override parameter" do
it "should use given override instead of the first alternative" do
@params = { "ab_test" => { "link_color" => "red" } }
expect(ab_test("link_color", "blue", "red")).to eq("red")
expect(ab_test("link_color", "blue", "red", "green")).to eq("red")
expect(ab_test("link_color", { "blue" => 0.01 }, "red" => 0.2)).to eq("red")
expect(ab_test("link_color", { "blue" => 0.8 }, { "red" => 20 })).to eq("red")
expect(ab_test("link_color", "blue", "red") do |alternative|
"shared/#{alternative}"
end).to eq("shared/red")
end
end
end
context "and preloaded config given" do
before do
Split.configuration.experiments[:link_color] = {
alternatives: [ "blue", "red" ],
}
end
it "uses first alternative" do
expect(ab_test(:link_color)).to eq("blue")
end
end
end
describe "finished" do
it "should not raise an exception" do
expect { ab_finished("link_color") }.not_to raise_error
end
it "should call db_failover_on_db_error proc with error as parameter" do
Split.configure do |config|
config.db_failover_on_db_error = proc do |error|
expect(error).to be_a(Errno::ECONNREFUSED)
end
end
expect(Split.configuration.db_failover_on_db_error).to receive(:call).and_call_original
ab_finished("link_color")
end
end
end
end
context "with preloaded config" do
before { Split.configuration.experiments = {} }
it "pulls options from config file" do
Split.configuration.experiments[:my_experiment] = {
alternatives: [ "control_opt", "other_opt" ],
goals: ["goal1", "goal2"]
}
ab_test :my_experiment
expect(Split::Experiment.new(:my_experiment).alternatives.map(&:name)).to eq([ "control_opt", "other_opt" ])
expect(Split::Experiment.new(:my_experiment).goals).to eq([ "goal1", "goal2" ])
end
it "can be called multiple times" do
Split.configuration.experiments[:my_experiment] = {
alternatives: [ "control_opt", "other_opt" ],
goals: ["goal1", "goal2"]
}
5.times { ab_test :my_experiment }
experiment = Split::Experiment.new(:my_experiment)
expect(experiment.alternatives.map(&:name)).to eq([ "control_opt", "other_opt" ])
expect(experiment.goals).to eq([ "goal1", "goal2" ])
expect(experiment.participant_count).to eq(1)
end
it "accepts multiple goals" do
Split.configuration.experiments[:my_experiment] = {
alternatives: [ "control_opt", "other_opt" ],
goals: [ "goal1", "goal2", "goal3" ]
}
ab_test :my_experiment
experiment = Split::Experiment.new(:my_experiment)
expect(experiment.goals).to eq([ "goal1", "goal2", "goal3" ])
end
it "allow specifying goals to be optional" do
Split.configuration.experiments[:my_experiment] = {
alternatives: [ "control_opt", "other_opt" ]
}
experiment = Split::Experiment.new(:my_experiment)
expect(experiment.goals).to eq([])
end
it "accepts multiple alternatives" do
Split.configuration.experiments[:my_experiment] = {
alternatives: [ "control_opt", "second_opt", "third_opt" ],
}
ab_test :my_experiment
experiment = Split::Experiment.new(:my_experiment)
expect(experiment.alternatives.map(&:name)).to eq([ "control_opt", "second_opt", "third_opt" ])
end
it "accepts probability on alternatives" do
Split.configuration.experiments[:my_experiment] = {
alternatives: [
{ name: "control_opt", percent: 67 },
{ name: "second_opt", percent: 10 },
{ name: "third_opt", percent: 23 },
],
}
ab_test :my_experiment
experiment = Split::Experiment.new(:my_experiment)
expect(experiment.alternatives.collect { |a| [a.name, a.weight] }).to eq([["control_opt", 0.67], ["second_opt", 0.1], ["third_opt", 0.23]])
end
it "accepts probability on some alternatives" do
Split.configuration.experiments[:my_experiment] = {
alternatives: [
{ name: "control_opt", percent: 34 },
"second_opt",
{ name: "third_opt", percent: 23 },
"fourth_opt",
],
}
ab_test :my_experiment
experiment = Split::Experiment.new(:my_experiment)
names_and_weights = experiment.alternatives.collect { |a| [a.name, a.weight] }
expect(names_and_weights).to eq([["control_opt", 0.34], ["second_opt", 0.215], ["third_opt", 0.23], ["fourth_opt", 0.215]])
expect(names_and_weights.inject(0) { |sum, nw| sum + nw[1] }).to eq(1.0)
end
it "allows name param without probability" do
Split.configuration.experiments[:my_experiment] = {
alternatives: [
{ name: "control_opt" },
"second_opt",
{ name: "third_opt", percent: 64 },
],
}
ab_test :my_experiment
experiment = Split::Experiment.new(:my_experiment)
names_and_weights = experiment.alternatives.collect { |a| [a.name, a.weight] }
expect(names_and_weights).to eq([["control_opt", 0.18], ["second_opt", 0.18], ["third_opt", 0.64]])
expect(names_and_weights.inject(0) { |sum, nw| sum + nw[1] }).to eq(1.0)
end
it "fails gracefully if config is missing experiment" do
Split.configuration.experiments = { other_experiment: { foo: "Bar" } }
expect { ab_test :my_experiment }.to raise_error(Split::ExperimentNotFound)
end
it "fails gracefully if config is missing" do
expect { Split.configuration.experiments = nil }.to raise_error(Split::InvalidExperimentsFormatError)
end
it "fails gracefully if config is missing alternatives" do
Split.configuration.experiments[:my_experiment] = { foo: "Bar" }
expect { ab_test :my_experiment }.to raise_error(NoMethodError)
end
end
it "should handle multiple experiments correctly" do
experiment2 = Split::ExperimentCatalog.find_or_create("link_color2", "blue", "red")
ab_test("link_color", "blue", "red")
ab_test("link_color2", "blue", "red")
ab_finished("link_color2")
experiment2.alternatives.each do |alt|
expect(alt.unfinished_count).to eq(0)
end
end
context "with goals" do
before do
@experiment = { "link_color" => ["purchase", "refund"] }
@alternatives = ["blue", "red"]
@experiment_name, @goals = normalize_metric(@experiment)
@goal1 = @goals[0]
@goal2 = @goals[1]
end
it "should normalize experiment" do
expect(@experiment_name).to eq("link_color")
expect(@goals).to eq(["purchase", "refund"])
end
describe "ab_test" do
it "should allow experiment goals interface as a single hash" do
ab_test(@experiment, *@alternatives)
experiment = Split::ExperimentCatalog.find("link_color")
expect(experiment.goals).to eq(["purchase", "refund"])
end
end
describe "ab_finished" do
before do
@alternative_name = ab_test(@experiment, *@alternatives)
end
it "should increment the counter for the specified-goal completed alternative" do
expect { ab_finished({ "link_color" => ["purchase"] }) }
.to change { Split::Alternative.new(@alternative_name, @experiment_name).completed_count(@goal2) }.by(0)
.and change { Split::Alternative.new(@alternative_name, @experiment_name).completed_count(@goal1) }.by(1)
end
end
end
end
<MSG> rename variants to alternatives
<DFF> @@ -597,7 +597,7 @@ describe Split::Helper do
it "accepts multiple goals" do
Split.configuration.experiments[:my_experiment] = {
- :variants => [ "control_opt", "other_opt" ],
+ :alternatives => [ "control_opt", "other_opt" ],
:goals => [ "goal1", "goal2", "goal3" ]
}
ab_test :my_experiment
@@ -607,7 +607,7 @@ describe Split::Helper do
it "allow specifying goals to be optional" do
Split.configuration.experiments[:my_experiment] = {
- :variants => [ "control_opt", "other_opt" ]
+ :alternatives => [ "control_opt", "other_opt" ]
}
experiment = Split::Experiment.find(:my_experiment)
experiment.goals.should == []
| 2 | rename variants to alternatives | 2 | .rb | rb | mit | splitrb/split |
10071880 | <NME> helper_spec.rb
<BEF> # frozen_string_literal: true
require "spec_helper"
# TODO change some of these tests to use Rack::Test
describe Split::Helper do
include Split::Helper
let(:experiment) {
Split::ExperimentCatalog.find_or_create("link_color", "blue", "red")
}
describe "ab_test" do
it "should not raise an error when passed strings for alternatives" do
expect { ab_test("xyz", "1", "2", "3") }.not_to raise_error
end
it "should not raise an error when passed an array for alternatives" do
expect { ab_test("xyz", ["1", "2", "3"]) }.not_to raise_error
end
it "should raise the appropriate error when passed integers for alternatives" do
expect { ab_test("xyz", 1, 2, 3) }.to raise_error(ArgumentError)
end
it "should raise the appropriate error when passed symbols for alternatives" do
expect { ab_test("xyz", :a, :b, :c) }.to raise_error(ArgumentError)
end
it "should not raise error when passed an array for goals" do
expect { ab_test({ "link_color" => ["purchase", "refund"] }, "blue", "red") }.not_to raise_error
end
it "should not raise error when passed just one goal" do
expect { ab_test({ "link_color" => "purchase" }, "blue", "red") }.not_to raise_error
end
it "raises an appropriate error when processing combined expirements" do
Split.configuration.experiments = {
combined_exp_1: {
alternatives: [ { name: "control", percent: 50 }, { name: "test-alt", percent: 50 } ],
metric: :my_metric,
combined_experiments: [:combined_exp_1_sub_1]
}
}
Split::ExperimentCatalog.find_or_create("combined_exp_1")
expect { ab_test("combined_exp_1") }.to raise_error(Split::InvalidExperimentsFormatError)
end
it "should assign a random alternative to a new user when there are an equal number of alternatives assigned" do
ab_test("link_color", "blue", "red")
expect(["red", "blue"]).to include(ab_user["link_color"])
end
it "should increment the participation counter after assignment to a new user" do
previous_red_count = Split::Alternative.new("red", "link_color").participant_count
previous_blue_count = Split::Alternative.new("blue", "link_color").participant_count
ab_test("link_color", "blue", "red")
new_red_count = Split::Alternative.new("red", "link_color").participant_count
new_blue_count = Split::Alternative.new("blue", "link_color").participant_count
expect((new_red_count + new_blue_count)).to eq(previous_red_count + previous_blue_count + 1)
end
it "should not increment the counter for an experiment that the user is not participating in" do
ab_test("link_color", "blue", "red")
e = Split::ExperimentCatalog.find_or_create("button_size", "small", "big")
expect {
# User shouldn't participate in this second experiment
ab_test("button_size", "small", "big")
}.not_to change { e.participant_count }
end
it "should not increment the counter for an ended experiment" do
e = Split::ExperimentCatalog.find_or_create("button_size", "small", "big")
e.winner = "small"
expect {
a = ab_test("button_size", "small", "big")
expect(a).to eq("small")
}.not_to change { e.participant_count }
end
it "should not increment the counter for an not started experiment" do
expect(Split.configuration).to receive(:start_manually).and_return(true)
e = Split::ExperimentCatalog.find_or_create("button_size", "small", "big")
expect {
a = ab_test("button_size", "small", "big")
expect(a).to eq("small")
}.not_to change { e.participant_count }
end
it "should return the given alternative for an existing user" do
expect(ab_test("link_color", "blue", "red")).to eq ab_test("link_color", "blue", "red")
end
it "should always return the winner if one is present" do
experiment.winner = "orange"
expect(ab_test("link_color", "blue", "red")).to eq("orange")
end
it "should allow the alternative to be forced by passing it in the params" do
# ?ab_test[link_color]=blue
@params = { "ab_test" => { "link_color" => "blue" } }
alternative = ab_test("link_color", "blue", "red")
expect(alternative).to eq("blue")
alternative = ab_test("link_color", { "blue" => 1 }, "red" => 5)
expect(alternative).to eq("blue")
@params = { "ab_test" => { "link_color" => "red" } }
alternative = ab_test("link_color", "blue", "red")
expect(alternative).to eq("red")
alternative = ab_test("link_color", { "blue" => 5 }, "red" => 1)
expect(alternative).to eq("red")
end
it "should not allow an arbitrary alternative" do
@params = { "ab_test" => { "link_color" => "pink" } }
alternative = ab_test("link_color", "blue")
expect(alternative).to eq("blue")
end
it "should not store the split when a param forced alternative" do
@params = { "ab_test" => { "link_color" => "blue" } }
expect(ab_user).not_to receive(:[]=)
ab_test("link_color", "blue", "red")
end
it "SPLIT_DISABLE query parameter should also force the alternative (uses control)" do
@params = { "SPLIT_DISABLE" => "true" }
alternative = ab_test("link_color", "blue", "red")
expect(alternative).to eq("blue")
alternative = ab_test("link_color", { "blue" => 1 }, "red" => 5)
expect(alternative).to eq("blue")
alternative = ab_test("link_color", "red", "blue")
expect(alternative).to eq("red")
alternative = ab_test("link_color", { "red" => 5 }, "blue" => 1)
expect(alternative).to eq("red")
end
it "should not store the split when Split generically disabled" do
@params = { "SPLIT_DISABLE" => "true" }
expect(ab_user).not_to receive(:[]=)
ab_test("link_color", "blue", "red")
end
context "when store_override is set" do
before { Split.configuration.store_override = true }
it "should store the forced alternative" do
@params = { "ab_test" => { "link_color" => "blue" } }
expect(ab_user).to receive(:[]=).with("link_color", "blue")
ab_test("link_color", "blue", "red")
end
end
context "when on_trial_choose is set" do
before { Split.configuration.on_trial_choose = :some_method }
it "should call the method" do
expect(self).to receive(:some_method)
ab_test("link_color", "blue", "red")
end
end
it "should allow passing a block" do
alt = ab_test("link_color", "blue", "red")
ret = ab_test("link_color", "blue", "red") { |alternative| "shared/#{alternative}" }
expect(ret).to eq("shared/#{alt}")
end
it "should allow the share of visitors see an alternative to be specified" do
ab_test("link_color", { "blue" => 0.8 }, { "red" => 20 })
expect(["red", "blue"]).to include(ab_user["link_color"])
end
it "should allow alternative weighting interface as a single hash" do
ab_test("link_color", { "blue" => 0.01 }, "red" => 0.2)
experiment = Split::ExperimentCatalog.find("link_color")
expect(experiment.alternatives.map(&:name)).to eq(["blue", "red"])
expect(experiment.alternatives.collect { |a| a.weight }).to match_array([0.01, 0.2])
end
it "should only let a user participate in one experiment at a time" do
link_color = ab_test("link_color", "blue", "red")
ab_test("button_size", "small", "big")
expect(ab_user["link_color"]).to eq(link_color)
big = Split::Alternative.new("big", "button_size")
expect(big.participant_count).to eq(0)
small = Split::Alternative.new("small", "button_size")
expect(small.participant_count).to eq(0)
end
it "should let a user participate in many experiment with allow_multiple_experiments option" do
Split.configure do |config|
config.allow_multiple_experiments = true
end
link_color = ab_test("link_color", "blue", "red")
button_size = ab_test("button_size", "small", "big")
expect(ab_user["link_color"]).to eq(link_color)
expect(ab_user["button_size"]).to eq(button_size)
button_size_alt = Split::Alternative.new(button_size, "button_size")
expect(button_size_alt.participant_count).to eq(1)
end
context "with allow_multiple_experiments = 'control'" do
it "should let a user participate in many experiment with one non-'control' alternative" do
Split.configure do |config|
config.allow_multiple_experiments = "control"
end
groups = 100.times.map do |n|
ab_test("test#{n}".to_sym, { "control" => (100 - n) }, { "test#{n}-alt" => n })
end
experiments = ab_user.active_experiments
expect(experiments.size).to be > 1
count_control = experiments.values.count { |g| g == "control" }
expect(count_control).to eq(experiments.size - 1)
count_alts = groups.count { |g| g != "control" }
expect(count_alts).to eq(1)
end
context "when user already has experiment" do
let(:mock_user) { Split::User.new(self, { "test_0" => "test-alt" }) }
before do
Split.configure do |config|
config.allow_multiple_experiments = "control"
end
Split::ExperimentCatalog.find_or_initialize("test_0", "control", "test-alt").save
Split::ExperimentCatalog.find_or_initialize("test_1", "control", "test-alt").save
end
it "should restore previously selected alternative" do
expect(ab_user.active_experiments.size).to eq 1
expect(ab_test(:test_0, { "control" => 100 }, { "test-alt" => 1 })).to eq "test-alt"
expect(ab_test(:test_0, { "control" => 1 }, { "test-alt" => 100 })).to eq "test-alt"
end
it "should select the correct alternatives after experiment resets" do
experiment = Split::ExperimentCatalog.find(:test_0)
experiment.reset
mock_user[experiment.key] = "test-alt"
expect(ab_user.active_experiments.size).to eq 1
expect(ab_test(:test_0, { "control" => 100 }, { "test-alt" => 1 })).to eq "test-alt"
expect(ab_test(:test_0, { "control" => 0 }, { "test-alt" => 100 })).to eq "test-alt"
end
it "lets override existing choice" do
pending "this requires user store reset on first call not depending on whelther it is current trial"
@params = { "ab_test" => { "test_1" => "test-alt" } }
expect(ab_test(:test_0, { "control" => 0 }, { "test-alt" => 100 })).to eq "control"
expect(ab_test(:test_1, { "control" => 100 }, { "test-alt" => 1 })).to eq "test-alt"
end
end
end
it "should not over-write a finished key when an experiment is on a later version" do
experiment.increment_version
ab_user = { experiment.key => "blue", experiment.finished_key => true }
finished_session = ab_user.dup
ab_test("link_color", "blue", "red")
expect(ab_user).to eq(finished_session)
end
end
describe "metadata" do
context "is defined" do
before do
Split.configuration.experiments = {
my_experiment: {
alternatives: ["one", "two"],
resettable: false,
metadata: { "one" => "Meta1", "two" => "Meta2" }
}
}
end
it "should be passed to helper block" do
@params = { "ab_test" => { "my_experiment" => "two" } }
expect(ab_test("my_experiment")).to eq "two"
expect(ab_test("my_experiment") do |alternative, meta|
meta
end).to eq("Meta2")
end
it "should pass control metadata helper block if library disabled" do
Split.configure do |config|
config.enabled = false
end
expect(ab_test("my_experiment")).to eq "one"
expect(ab_test("my_experiment") do |_, meta|
meta
end).to eq("Meta1")
end
end
context "is not defined" do
before do
Split.configuration.experiments = {
my_experiment: {
alternatives: ["one", "two"],
resettable: false,
metadata: nil
}
}
end
it "should be passed to helper block" do
expect(ab_test("my_experiment") do |alternative, meta|
meta
end).to eq({})
end
it "should pass control metadata helper block if library disabled" do
Split.configure do |config|
config.enabled = false
end
expect(ab_test("my_experiment") do |_, meta|
meta
end).to eq({})
end
end
end
describe "ab_finished" do
context "for an experiment that the user participates in" do
before(:each) do
@experiment_name = "link_color"
@alternatives = ["blue", "red"]
@experiment = Split::ExperimentCatalog.find_or_create(@experiment_name, *@alternatives)
@alternative_name = ab_test(@experiment_name, *@alternatives)
@previous_completion_count = Split::Alternative.new(@alternative_name, @experiment_name).completed_count
end
it "should increment the counter for the completed alternative" do
ab_finished(@experiment_name)
new_completion_count = Split::Alternative.new(@alternative_name, @experiment_name).completed_count
expect(new_completion_count).to eq(@previous_completion_count + 1)
end
it "should set experiment's finished key if reset is false" do
ab_finished(@experiment_name, { reset: false })
expect(ab_user[@experiment.key]).to eq(@alternative_name)
expect(ab_user[@experiment.finished_key]).to eq(true)
end
it "should not increment the counter if reset is false and the experiment has been already finished" do
2.times { ab_finished(@experiment_name, { reset: false }) }
new_completion_count = Split::Alternative.new(@alternative_name, @experiment_name).completed_count
expect(new_completion_count).to eq(@previous_completion_count + 1)
end
it "should not increment the counter for an ended experiment" do
e = Split::ExperimentCatalog.find_or_create("button_size", "small", "big")
e.winner = "small"
a = ab_test("button_size", "small", "big")
expect(a).to eq("small")
expect {
ab_finished("button_size")
}.not_to change { Split::Alternative.new(a, "button_size").completed_count }
end
it "should clear out the user's participation from their session" do
expect(ab_user[@experiment.key]).to eq(@alternative_name)
ab_finished(@experiment_name)
expect(ab_user.keys).to be_empty
end
it "should not clear out the users session if reset is false" do
expect(ab_user[@experiment.key]).to eq(@alternative_name)
ab_finished(@experiment_name, { reset: false })
expect(ab_user[@experiment.key]).to eq(@alternative_name)
expect(ab_user[@experiment.finished_key]).to eq(true)
end
it "should reset the users session when experiment is not versioned" do
expect(ab_user[@experiment.key]).to eq(@alternative_name)
ab_finished(@experiment_name)
expect(ab_user.keys).to be_empty
end
it "should reset the users session when experiment is versioned" do
@experiment.increment_version
@alternative_name = ab_test(@experiment_name, *@alternatives)
expect(ab_user[@experiment.key]).to eq(@alternative_name)
ab_finished(@experiment_name)
expect(ab_user.keys).to be_empty
end
context "when on_trial_complete is set" do
before { Split.configuration.on_trial_complete = :some_method }
it "should call the method" do
expect(self).to receive(:some_method)
ab_finished(@experiment_name)
end
it "should not call the method without alternative" do
ab_user[@experiment.key] = nil
expect(self).not_to receive(:some_method)
ab_finished(@experiment_name)
end
end
end
context "for an experiment that the user is excluded from" do
before do
alternative = ab_test("link_color", "blue", "red")
expect(Split::Alternative.new(alternative, "link_color").participant_count).to eq(1)
alternative = ab_test("button_size", "small", "big")
expect(Split::Alternative.new(alternative, "button_size").participant_count).to eq(0)
end
it "should not increment the completed counter" do
# So, user should be participating in the link_color experiment and
# receive the control for button_size. As the user is not participating in
# the button size experiment, finishing it should not increase the
# completion count for that alternative.
expect {
ab_finished("button_size")
}.not_to change { Split::Alternative.new("small", "button_size").completed_count }
end
end
context "for an experiment that the user does not participate in" do
before do
Split::ExperimentCatalog.find_or_create(:not_started_experiment, "control", "alt")
end
it "should not raise an exception" do
expect { ab_finished(:not_started_experiment) }.not_to raise_exception
end
it "should not change the user state when reset is false" do
expect { ab_finished(:not_started_experiment, reset: false) }.not_to change { ab_user.keys }.from([])
end
it "should not change the user state when reset is true" do
expect(self).not_to receive(:reset!)
ab_finished(:not_started_experiment)
end
it "should not increment the completed counter" do
ab_finished(:not_started_experiment)
expect(Split::Alternative.new("control", :not_started_experiment).completed_count).to eq(0)
expect(Split::Alternative.new("alt", :not_started_experiment).completed_count).to eq(0)
end
end
end
context "finished with config" do
it "passes reset option" do
Split.configuration.experiments = {
my_experiment: {
alternatives: ["one", "two"],
resettable: false,
}
}
alternative = ab_test(:my_experiment)
experiment = Split::ExperimentCatalog.find :my_experiment
ab_finished :my_experiment
expect(ab_user[experiment.key]).to eq(alternative)
expect(ab_user[experiment.finished_key]).to eq(true)
end
end
context "finished with metric name" do
before { Split.configuration.experiments = {} }
before { expect(Split::Alternative).to receive(:new).at_least(1).times.and_call_original }
def should_finish_experiment(experiment_name, should_finish = true)
alts = Split.configuration.experiments[experiment_name][:alternatives]
experiment = Split::ExperimentCatalog.find_or_create(experiment_name, *alts)
alt_name = ab_user[experiment.key] = alts.first
alt = double("alternative")
expect(alt).to receive(:name).at_most(1).times.and_return(alt_name)
expect(Split::Alternative).to receive(:new).at_most(1).times.with(alt_name, experiment_name.to_s).and_return(alt)
if should_finish
expect(alt).to receive(:increment_completion).at_most(1).times
else
expect(alt).not_to receive(:increment_completion)
end
end
it "completes the test" do
Split.configuration.experiments[:my_experiment] = {
alternatives: [ "control_opt", "other_opt" ],
metric: :my_metric
}
should_finish_experiment :my_experiment
ab_finished :my_metric
end
it "completes all relevant tests" do
Split.configuration.experiments = {
exp_1: {
alternatives: [ "1-1", "1-2" ],
metric: :my_metric
},
exp_2: {
alternatives: [ "2-1", "2-2" ],
metric: :another_metric
},
exp_3: {
alternatives: [ "3-1", "3-2" ],
metric: :my_metric
},
}
should_finish_experiment :exp_1
should_finish_experiment :exp_2, false
should_finish_experiment :exp_3
ab_finished :my_metric
end
it "passes reset option" do
Split.configuration.experiments = {
my_exp: {
alternatives: ["one", "two"],
metric: :my_metric,
resettable: false,
}
}
alternative_name = ab_test(:my_exp)
exp = Split::ExperimentCatalog.find :my_exp
ab_finished :my_metric
expect(ab_user[exp.key]).to eq(alternative_name)
expect(ab_user[exp.finished_key]).to be_truthy
end
it "passes through options" do
Split.configuration.experiments = {
my_exp: {
alternatives: ["one", "two"],
metric: :my_metric,
}
}
alternative_name = ab_test(:my_exp)
exp = Split::ExperimentCatalog.find :my_exp
ab_finished :my_metric, reset: false
expect(ab_user[exp.key]).to eq(alternative_name)
expect(ab_user[exp.finished_key]).to be_truthy
end
end
describe "conversions" do
it "should return a conversion rate for an alternative" do
alternative_name = ab_test("link_color", "blue", "red")
previous_convertion_rate = Split::Alternative.new(alternative_name, "link_color").conversion_rate
expect(previous_convertion_rate).to eq(0.0)
ab_finished("link_color")
new_convertion_rate = Split::Alternative.new(alternative_name, "link_color").conversion_rate
expect(new_convertion_rate).to eq(1.0)
end
end
describe "active experiments" do
it "should show an active test" do
alternative = ab_test("def", "4", "5", "6")
expect(active_experiments.count).to eq 1
expect(active_experiments.first[0]).to eq "def"
expect(active_experiments.first[1]).to eq alternative
end
it "should show a finished test" do
alternative = ab_test("def", "4", "5", "6")
ab_finished("def", { reset: false })
expect(active_experiments.count).to eq 1
expect(active_experiments.first[0]).to eq "def"
expect(active_experiments.first[1]).to eq alternative
end
it "should show an active test when an experiment is on a later version" do
experiment.reset
expect(experiment.version).to eq(1)
ab_test("link_color", "blue", "red")
expect(active_experiments.count).to eq 1
expect(active_experiments.first[0]).to eq "link_color"
it "accepts multiple goals" do
Split.configuration.experiments[:my_experiment] = {
:variants => [ "control_opt", "other_opt" ],
:goals => [ "goal1", "goal2", "goal3" ]
}
ab_test :my_experiment
expect(experiment.version).to eq(10)
expect(active_experiments.count).to eq 1
it "allow specifying goals to be optional" do
Split.configuration.experiments[:my_experiment] = {
:variants => [ "control_opt", "other_opt" ]
}
experiment = Split::Experiment.find(:my_experiment)
experiment.goals.should == []
alternative = ab_test("def", "4", "5", "6")
another_alternative = ab_test("ghi", "7", "8", "9")
expect(active_experiments.count).to eq 2
expect(active_experiments["def"]).to eq alternative
expect(active_experiments["ghi"]).to eq another_alternative
end
it "should not show tests with winners" do
Split.configure do |config|
config.allow_multiple_experiments = true
end
e = Split::ExperimentCatalog.find_or_create("def", "4", "5", "6")
e.winner = "4"
ab_test("def", "4", "5", "6")
another_alternative = ab_test("ghi", "7", "8", "9")
expect(active_experiments.count).to eq 1
expect(active_experiments.first[0]).to eq "ghi"
expect(active_experiments.first[1]).to eq another_alternative
end
end
describe "when user is a robot" do
before(:each) do
@request = OpenStruct.new(user_agent: "Googlebot/2.1 (+http://www.google.com/bot.html)")
end
describe "ab_test" do
it "should return the control" do
alternative = ab_test("link_color", "blue", "red")
expect(alternative).to eq experiment.control.name
end
it "should not create a experiment" do
ab_test("link_color", "blue", "red")
expect(Split::Experiment.new("link_color")).to be_a_new_record
end
it "should not increment the participation count" do
previous_red_count = Split::Alternative.new("red", "link_color").participant_count
previous_blue_count = Split::Alternative.new("blue", "link_color").participant_count
ab_test("link_color", "blue", "red")
new_red_count = Split::Alternative.new("red", "link_color").participant_count
new_blue_count = Split::Alternative.new("blue", "link_color").participant_count
expect((new_red_count + new_blue_count)).to eq(previous_red_count + previous_blue_count)
end
end
describe "finished" do
it "should not increment the completed count" do
alternative_name = ab_test("link_color", "blue", "red")
previous_completion_count = Split::Alternative.new(alternative_name, "link_color").completed_count
ab_finished("link_color")
new_completion_count = Split::Alternative.new(alternative_name, "link_color").completed_count
expect(new_completion_count).to eq(previous_completion_count)
end
end
end
describe "when providing custom ignore logic" do
context "using a proc to configure custom logic" do
before(:each) do
Split.configure do |c|
c.ignore_filter = proc { |request| true } # ignore everything
end
end
it "ignores the ab_test" do
ab_test("link_color", "blue", "red")
red_count = Split::Alternative.new("red", "link_color").participant_count
blue_count = Split::Alternative.new("blue", "link_color").participant_count
expect((red_count + blue_count)).to be(0)
end
end
end
shared_examples_for "a disabled test" do
describe "ab_test" do
it "should return the control" do
alternative = ab_test("link_color", "blue", "red")
expect(alternative).to eq experiment.control.name
end
it "should not increment the participation count" do
previous_red_count = Split::Alternative.new("red", "link_color").participant_count
previous_blue_count = Split::Alternative.new("blue", "link_color").participant_count
ab_test("link_color", "blue", "red")
new_red_count = Split::Alternative.new("red", "link_color").participant_count
new_blue_count = Split::Alternative.new("blue", "link_color").participant_count
expect((new_red_count + new_blue_count)).to eq(previous_red_count + previous_blue_count)
end
end
describe "finished" do
it "should not increment the completed count" do
alternative_name = ab_test("link_color", "blue", "red")
previous_completion_count = Split::Alternative.new(alternative_name, "link_color").completed_count
ab_finished("link_color")
new_completion_count = Split::Alternative.new(alternative_name, "link_color").completed_count
expect(new_completion_count).to eq(previous_completion_count)
end
end
end
describe "when ip address is ignored" do
context "individually" do
before(:each) do
@request = OpenStruct.new(ip: "81.19.48.130")
Split.configure do |c|
c.ignore_ip_addresses << "81.19.48.130"
end
end
it_behaves_like "a disabled test"
end
context "for a range" do
before(:each) do
@request = OpenStruct.new(ip: "81.19.48.129")
Split.configure do |c|
c.ignore_ip_addresses << /81\.19\.48\.[0-9]+/
end
end
it_behaves_like "a disabled test"
end
context "using both a range and a specific value" do
before(:each) do
@request = OpenStruct.new(ip: "81.19.48.128")
Split.configure do |c|
c.ignore_ip_addresses << "81.19.48.130"
c.ignore_ip_addresses << /81\.19\.48\.[0-9]+/
end
end
it_behaves_like "a disabled test"
end
context "when ignored other address" do
before do
@request = OpenStruct.new(ip: "1.1.1.1")
Split.configure do |c|
c.ignore_ip_addresses << "81.19.48.130"
end
end
it "works as usual" do
alternative_name = ab_test("link_color", "red", "blue")
expect {
ab_finished("link_color")
}.to change(Split::Alternative.new(alternative_name, "link_color"), :completed_count).by(1)
end
end
end
describe "when user is previewing" do
before(:each) do
@request = OpenStruct.new(headers: { "x-purpose" => "preview" })
end
it_behaves_like "a disabled test"
end
describe "versioned experiments" do
it "should use version zero if no version is present" do
alternative_name = ab_test("link_color", "blue", "red")
expect(experiment.version).to eq(0)
expect(ab_user["link_color"]).to eq(alternative_name)
end
it "should save the version of the experiment to the session" do
experiment.reset
expect(experiment.version).to eq(1)
alternative_name = ab_test("link_color", "blue", "red")
expect(ab_user["link_color:1"]).to eq(alternative_name)
end
it "should load the experiment even if the version is not 0" do
experiment.reset
expect(experiment.version).to eq(1)
alternative_name = ab_test("link_color", "blue", "red")
expect(ab_user["link_color:1"]).to eq(alternative_name)
return_alternative_name = ab_test("link_color", "blue", "red")
expect(return_alternative_name).to eq(alternative_name)
end
it "should reset the session of a user on an older version of the experiment" do
alternative_name = ab_test("link_color", "blue", "red")
expect(ab_user["link_color"]).to eq(alternative_name)
alternative = Split::Alternative.new(alternative_name, "link_color")
expect(alternative.participant_count).to eq(1)
experiment.reset
expect(experiment.version).to eq(1)
alternative = Split::Alternative.new(alternative_name, "link_color")
expect(alternative.participant_count).to eq(0)
new_alternative_name = ab_test("link_color", "blue", "red")
expect(ab_user["link_color:1"]).to eq(new_alternative_name)
new_alternative = Split::Alternative.new(new_alternative_name, "link_color")
expect(new_alternative.participant_count).to eq(1)
end
it "should cleanup old versions of experiments from the session" do
alternative_name = ab_test("link_color", "blue", "red")
expect(ab_user["link_color"]).to eq(alternative_name)
alternative = Split::Alternative.new(alternative_name, "link_color")
expect(alternative.participant_count).to eq(1)
experiment.reset
expect(experiment.version).to eq(1)
alternative = Split::Alternative.new(alternative_name, "link_color")
expect(alternative.participant_count).to eq(0)
new_alternative_name = ab_test("link_color", "blue", "red")
expect(ab_user["link_color:1"]).to eq(new_alternative_name)
end
it "should only count completion of users on the current version" do
alternative_name = ab_test("link_color", "blue", "red")
expect(ab_user["link_color"]).to eq(alternative_name)
Split::Alternative.new(alternative_name, "link_color")
experiment.reset
expect(experiment.version).to eq(1)
ab_finished("link_color")
alternative = Split::Alternative.new(alternative_name, "link_color")
expect(alternative.completed_count).to eq(0)
end
end
context "when redis is not available" do
before(:each) do
expect(Split).to receive(:redis).at_most(5).times.and_raise(Errno::ECONNREFUSED.new)
end
context "and db_failover config option is turned off" do
before(:each) do
Split.configure do |config|
config.db_failover = false
end
end
describe "ab_test" do
it "should raise an exception" do
expect { ab_test("link_color", "blue", "red") }.to raise_error(Errno::ECONNREFUSED)
end
end
describe "finished" do
it "should raise an exception" do
expect { ab_finished("link_color") }.to raise_error(Errno::ECONNREFUSED)
end
end
describe "disable split testing" do
before(:each) do
Split.configure do |config|
config.enabled = false
end
end
it "should not attempt to connect to redis" do
expect { ab_test("link_color", "blue", "red") }.not_to raise_error
end
it "should return control variable" do
expect(ab_test("link_color", "blue", "red")).to eq("blue")
expect { ab_finished("link_color") }.not_to raise_error
end
end
end
context "and db_failover config option is turned on" do
before(:each) do
Split.configure do |config|
config.db_failover = true
end
end
describe "ab_test" do
it "should not raise an exception" do
expect { ab_test("link_color", "blue", "red") }.not_to raise_error
end
it "should call db_failover_on_db_error proc with error as parameter" do
Split.configure do |config|
config.db_failover_on_db_error = proc do |error|
expect(error).to be_a(Errno::ECONNREFUSED)
end
end
expect(Split.configuration.db_failover_on_db_error).to receive(:call).and_call_original
ab_test("link_color", "blue", "red")
end
it "should always use first alternative" do
expect(ab_test("link_color", "blue", "red")).to eq("blue")
expect(ab_test("link_color", { "blue" => 0.01 }, "red" => 0.2)).to eq("blue")
expect(ab_test("link_color", { "blue" => 0.8 }, { "red" => 20 })).to eq("blue")
expect(ab_test("link_color", "blue", "red") do |alternative|
"shared/#{alternative}"
end).to eq("shared/blue")
end
context "and db_failover_allow_parameter_override config option is turned on" do
before(:each) do
Split.configure do |config|
config.db_failover_allow_parameter_override = true
end
end
context "and given an override parameter" do
it "should use given override instead of the first alternative" do
@params = { "ab_test" => { "link_color" => "red" } }
expect(ab_test("link_color", "blue", "red")).to eq("red")
expect(ab_test("link_color", "blue", "red", "green")).to eq("red")
expect(ab_test("link_color", { "blue" => 0.01 }, "red" => 0.2)).to eq("red")
expect(ab_test("link_color", { "blue" => 0.8 }, { "red" => 20 })).to eq("red")
expect(ab_test("link_color", "blue", "red") do |alternative|
"shared/#{alternative}"
end).to eq("shared/red")
end
end
end
context "and preloaded config given" do
before do
Split.configuration.experiments[:link_color] = {
alternatives: [ "blue", "red" ],
}
end
it "uses first alternative" do
expect(ab_test(:link_color)).to eq("blue")
end
end
end
describe "finished" do
it "should not raise an exception" do
expect { ab_finished("link_color") }.not_to raise_error
end
it "should call db_failover_on_db_error proc with error as parameter" do
Split.configure do |config|
config.db_failover_on_db_error = proc do |error|
expect(error).to be_a(Errno::ECONNREFUSED)
end
end
expect(Split.configuration.db_failover_on_db_error).to receive(:call).and_call_original
ab_finished("link_color")
end
end
end
end
context "with preloaded config" do
before { Split.configuration.experiments = {} }
it "pulls options from config file" do
Split.configuration.experiments[:my_experiment] = {
alternatives: [ "control_opt", "other_opt" ],
goals: ["goal1", "goal2"]
}
ab_test :my_experiment
expect(Split::Experiment.new(:my_experiment).alternatives.map(&:name)).to eq([ "control_opt", "other_opt" ])
expect(Split::Experiment.new(:my_experiment).goals).to eq([ "goal1", "goal2" ])
end
it "can be called multiple times" do
Split.configuration.experiments[:my_experiment] = {
alternatives: [ "control_opt", "other_opt" ],
goals: ["goal1", "goal2"]
}
5.times { ab_test :my_experiment }
experiment = Split::Experiment.new(:my_experiment)
expect(experiment.alternatives.map(&:name)).to eq([ "control_opt", "other_opt" ])
expect(experiment.goals).to eq([ "goal1", "goal2" ])
expect(experiment.participant_count).to eq(1)
end
it "accepts multiple goals" do
Split.configuration.experiments[:my_experiment] = {
alternatives: [ "control_opt", "other_opt" ],
goals: [ "goal1", "goal2", "goal3" ]
}
ab_test :my_experiment
experiment = Split::Experiment.new(:my_experiment)
expect(experiment.goals).to eq([ "goal1", "goal2", "goal3" ])
end
it "allow specifying goals to be optional" do
Split.configuration.experiments[:my_experiment] = {
alternatives: [ "control_opt", "other_opt" ]
}
experiment = Split::Experiment.new(:my_experiment)
expect(experiment.goals).to eq([])
end
it "accepts multiple alternatives" do
Split.configuration.experiments[:my_experiment] = {
alternatives: [ "control_opt", "second_opt", "third_opt" ],
}
ab_test :my_experiment
experiment = Split::Experiment.new(:my_experiment)
expect(experiment.alternatives.map(&:name)).to eq([ "control_opt", "second_opt", "third_opt" ])
end
it "accepts probability on alternatives" do
Split.configuration.experiments[:my_experiment] = {
alternatives: [
{ name: "control_opt", percent: 67 },
{ name: "second_opt", percent: 10 },
{ name: "third_opt", percent: 23 },
],
}
ab_test :my_experiment
experiment = Split::Experiment.new(:my_experiment)
expect(experiment.alternatives.collect { |a| [a.name, a.weight] }).to eq([["control_opt", 0.67], ["second_opt", 0.1], ["third_opt", 0.23]])
end
it "accepts probability on some alternatives" do
Split.configuration.experiments[:my_experiment] = {
alternatives: [
{ name: "control_opt", percent: 34 },
"second_opt",
{ name: "third_opt", percent: 23 },
"fourth_opt",
],
}
ab_test :my_experiment
experiment = Split::Experiment.new(:my_experiment)
names_and_weights = experiment.alternatives.collect { |a| [a.name, a.weight] }
expect(names_and_weights).to eq([["control_opt", 0.34], ["second_opt", 0.215], ["third_opt", 0.23], ["fourth_opt", 0.215]])
expect(names_and_weights.inject(0) { |sum, nw| sum + nw[1] }).to eq(1.0)
end
it "allows name param without probability" do
Split.configuration.experiments[:my_experiment] = {
alternatives: [
{ name: "control_opt" },
"second_opt",
{ name: "third_opt", percent: 64 },
],
}
ab_test :my_experiment
experiment = Split::Experiment.new(:my_experiment)
names_and_weights = experiment.alternatives.collect { |a| [a.name, a.weight] }
expect(names_and_weights).to eq([["control_opt", 0.18], ["second_opt", 0.18], ["third_opt", 0.64]])
expect(names_and_weights.inject(0) { |sum, nw| sum + nw[1] }).to eq(1.0)
end
it "fails gracefully if config is missing experiment" do
Split.configuration.experiments = { other_experiment: { foo: "Bar" } }
expect { ab_test :my_experiment }.to raise_error(Split::ExperimentNotFound)
end
it "fails gracefully if config is missing" do
expect { Split.configuration.experiments = nil }.to raise_error(Split::InvalidExperimentsFormatError)
end
it "fails gracefully if config is missing alternatives" do
Split.configuration.experiments[:my_experiment] = { foo: "Bar" }
expect { ab_test :my_experiment }.to raise_error(NoMethodError)
end
end
it "should handle multiple experiments correctly" do
experiment2 = Split::ExperimentCatalog.find_or_create("link_color2", "blue", "red")
ab_test("link_color", "blue", "red")
ab_test("link_color2", "blue", "red")
ab_finished("link_color2")
experiment2.alternatives.each do |alt|
expect(alt.unfinished_count).to eq(0)
end
end
context "with goals" do
before do
@experiment = { "link_color" => ["purchase", "refund"] }
@alternatives = ["blue", "red"]
@experiment_name, @goals = normalize_metric(@experiment)
@goal1 = @goals[0]
@goal2 = @goals[1]
end
it "should normalize experiment" do
expect(@experiment_name).to eq("link_color")
expect(@goals).to eq(["purchase", "refund"])
end
describe "ab_test" do
it "should allow experiment goals interface as a single hash" do
ab_test(@experiment, *@alternatives)
experiment = Split::ExperimentCatalog.find("link_color")
expect(experiment.goals).to eq(["purchase", "refund"])
end
end
describe "ab_finished" do
before do
@alternative_name = ab_test(@experiment, *@alternatives)
end
it "should increment the counter for the specified-goal completed alternative" do
expect { ab_finished({ "link_color" => ["purchase"] }) }
.to change { Split::Alternative.new(@alternative_name, @experiment_name).completed_count(@goal2) }.by(0)
.and change { Split::Alternative.new(@alternative_name, @experiment_name).completed_count(@goal1) }.by(1)
end
end
end
end
<MSG> rename variants to alternatives
<DFF> @@ -597,7 +597,7 @@ describe Split::Helper do
it "accepts multiple goals" do
Split.configuration.experiments[:my_experiment] = {
- :variants => [ "control_opt", "other_opt" ],
+ :alternatives => [ "control_opt", "other_opt" ],
:goals => [ "goal1", "goal2", "goal3" ]
}
ab_test :my_experiment
@@ -607,7 +607,7 @@ describe Split::Helper do
it "allow specifying goals to be optional" do
Split.configuration.experiments[:my_experiment] = {
- :variants => [ "control_opt", "other_opt" ]
+ :alternatives => [ "control_opt", "other_opt" ]
}
experiment = Split::Experiment.find(:my_experiment)
experiment.goals.should == []
| 2 | rename variants to alternatives | 2 | .rb | rb | mit | splitrb/split |
10071881 | <NME> stylesheet.ts
<BEF> import { strictEqual as equal, ok } from 'assert';
import { stylesheet as expandAbbreviation, resolveConfig, CSSAbbreviationScope } from '../src';
import score from '../src/stylesheet/score';
const defaultConfig = resolveConfig({
type: 'stylesheet',
options: {
'output.field': (index, placeholder) => `\${${index}${placeholder ? ':' + placeholder : ''}}`,
'stylesheet.fuzzySearchMinScore': 0
},
snippets: {
mten: 'margin: 10px;',
fsz: 'font-size',
gt: 'grid-template: repeat(2,auto) / repeat(auto-fit, minmax(250px, 1fr))'
},
cache: {},
});
function expand(abbr: string, config = defaultConfig) {
return expandAbbreviation(abbr, config);
}
describe('Stylesheet abbreviations', () => {
describe('Scoring', () => {
const pick = (abbr: string, items: string[]) => items
.map(item => ({ item, score: score(abbr, item, true) }))
.filter(obj => obj.score)
.sort((a, b) => b.score - a.score)
.map(obj => obj.item)[0];
it('compare scores', () => {
equal(score('aaa', 'aaa'), 1);
equal(score('baa', 'aaa'), 0);
ok(!score('b', 'aaa'));
ok(score('a', 'aaa'));
ok(score('a', 'abc'));
ok(score('ac', 'abc'));
ok(score('a', 'aaa') < score('aa', 'aaa'));
ok(score('ab', 'abc') > score('ab', 'acb'));
// acronym bonus
ok(score('ab', 'a-b') > score('ab', 'acb'));
});
it('pick padding or position', () => {
const items = ['p', 'pb', 'pl', 'pos', 'pa', 'oa', 'soa', 'pr', 'pt'];
equal(pick('p', items), 'p');
equal(pick('poa', items), 'pos');
});
});
it('keywords', () => {
equal(expand('bd1-s'), 'border: 1px solid;');
equal(expand('dib'), 'display: inline-block;');
equal(expand('bxsz'), 'box-sizing: ${1:border-box};');
equal(expand('bxz'), 'box-sizing: ${1:border-box};');
equal(expand('bxzc'), 'box-sizing: content-box;');
equal(expand('fl'), 'float: ${1:left};');
equal(expand('fll'), 'float: left;');
equal(expand('pos'), 'position: ${1:relative};');
equal(expand('poa'), 'position: absolute;');
equal(expand('por'), 'position: relative;');
equal(expand('pof'), 'position: fixed;');
equal(expand('pos-a'), 'position: absolute;');
equal(expand('m'), 'margin: ${0};');
equal(expand('m0'), 'margin: 0;');
// use `auto` as global keyword
equal(expand('m0-a'), 'margin: 0 auto;');
equal(expand('m-a'), 'margin: auto;');
equal(expand('bg'), 'background: ${1:#000};');
equal(expand('bd'), 'border: ${1:1px} ${2:solid} ${3:#000};');
equal(expand('bd0-s#fc0'), 'border: 0 solid #fc0;');
equal(expand('bd0-dd#fc0'), 'border: 0 dot-dash #fc0;');
equal(expand('bd0-h#fc0'), 'border: 0 hidden #fc0;');
equal(expand('trf-trs'), 'transform: translate(${1:x}, ${2:y});');
// https://github.com/emmetio/emmet/issues/610
equal(expand('c'), 'color: ${1:#000};');
equal(expand('cr'), 'color: rgb(${1:0}, ${2:0}, ${3:0});');
equal(expand('cra'), 'color: rgba(${1:0}, ${2:0}, ${3:0}, ${4:.5});');
// https://github.com/emmetio/emmet/issues/647
equal(expand('gtc'), 'grid-template-columns: repeat(${0});');
equal(expand('gtr'), 'grid-template-rows: repeat(${0});');
equal(expand('lis:n'), 'list-style: none;');
equal(expand('list:n'), 'list-style-type: none;');
equal(expand('bdt:n'), 'border-top: none;');
equal(expand('bgi:n'), 'background-image: none;');
equal(expand('q:n'), 'quotes: none;');
});
it('numeric', () => {
equal(expand('p0'), 'padding: 0;', 'No unit for 0');
equal(expand('p10'), 'padding: 10px;', '`px` unit for integers');
equal(expand('p.4'), 'padding: 0.4em;', '`em` for floats');
equal(expand('fz10'), 'font-size: 10px;', '`px` for integers');
equal(expand('fz1.'), 'font-size: 1em;', '`em` for explicit float');
equal(expand('p10p'), 'padding: 10%;', 'unit alias');
equal(expand('z10'), 'z-index: 10;', 'Unitless property');
equal(expand('p10r'), 'padding: 10rem;', 'unit alias');
equal(expand('mten'), 'margin: 10px;', 'Ignore terminating `;` in snippet');
// https://github.com/microsoft/vscode/issues/59951
equal(expand('fz'), 'font-size: ${0};');
equal(expand('fz12'), 'font-size: 12px;');
equal(expand('fsz'), 'font-size: ${0};');
equal(expand('fsz12'), 'font-size: 12px;');
equal(expand('fs'), 'font-style: ${1:italic};');
// https://github.com/emmetio/emmet/issues/558
equal(expand('us'), 'user-select: none;');
// https://github.com/microsoft/vscode/issues/105697
equal(expand('opa1'), 'opacity: 1;', 'Unitless property');
equal(expand('opa.1'), 'opacity: 0.1;', 'Unitless property');
equal(expand('opa.a'), 'opacity: .a;', 'Unitless property');
});
it('numeric with format options', () => {
const config = resolveConfig({
type: 'stylesheet',
options: {
'stylesheet.intUnit': 'pt',
'stylesheet.floatUnit': 'vh',
'stylesheet.unitAliases': {
equal(expand('trf:rx'), 'transform: rotateX(${1:angle});');
});
it('use min score when finding best match for snippets', () => {
equal(expand('auto', resolveConfig({ options: { 'stylesheet.fuzzySearchMinScore': 0 } })), 'align-self: unset;');
equal(expand('auto', resolveConfig({ options: { 'stylesheet.fuzzySearchMinScore': 0.3 } })), 'auto: ;');
equal(expand('z10', config), 'z-index: 10;', 'Unitless property');
equal(expand('p10r', config), 'padding: 10 / @rem;', 'unit alias');
});
it('important', () => {
equal(expand('!'), '!important');
equal(expand('p!'), 'padding: ${0} !important;');
equal(expand('p0!'), 'padding: 0 !important;');
});
it('color', () => {
equal(expand('c'), 'color: ${1:#000};');
equal(expand('c#'), 'color: #000;');
equal(expand('c#f.5'), 'color: rgba(255, 255, 255, 0.5);');
equal(expand('c#f.5!'), 'color: rgba(255, 255, 255, 0.5) !important;');
equal(expand('bgc'), 'background-color: #${1:fff};');
});
it('snippets', () => {
equal(expand('@'), '@media ${1:screen} {\n\t${0}\n}');
// Insert value into snippet fields
equal(expand('@k-name'), '@keyframes name {\n\t${2}\n}');
equal(expand('@k-name10'), '@keyframes name {\n\t10\n}');
equal(expand('gt'), 'grid-template: repeat(2, auto) / repeat(auto-fit, minmax(250px, 1fr));');
});
it('multiple properties', () => {
equal(expand('p10+m10-20'), 'padding: 10px;\nmargin: 10px 20px;');
equal(expand('p+bd'), 'padding: ${0};\nborder: ${1:1px} ${2:solid} ${3:#000};');
});
it('functions', () => {
equal(expand('trf-s(2)'), 'transform: scale(2, ${2:y});');
equal(expand('trf-s(2, 3)'), 'transform: scale(2, 3);');
});
it('case insensitive matches', () => {
equal(expand('trf:rx'), 'transform: rotateX(${1:angle});');
});
it('gradient resolver', () => {
equal(expand('lg'), 'background-image: linear-gradient(${0});');
equal(expand('lg(to right, #0, #f00.5)'), 'background-image: linear-gradient(to right, #000, rgba(255, 0, 0, 0.5));');
});
it('unmatched abbreviation', () => {
// This example is useless: it’s unexpected to receive `align-self: unset`
// for `auto` snippet
// equal(expand('auto', resolveConfig({
// type: 'stylesheet',
// options: { 'stylesheet.fuzzySearchMinScore': 0 }
// })), 'align-self: unset;');
equal(expand('auto'), 'auto: ${0};');
});
it('CSS-in-JS', () => {
const config = resolveConfig({
type: 'stylesheet',
options: {
'stylesheet.json': true,
'stylesheet.between': ': '
}
});
equal(expand('p10+mt10-20', config), 'padding: 10,\nmarginTop: \'10px 20px\',');
equal(expand('bgc', config), 'backgroundColor: \'#fff\',');
});
it('resolve context value', () => {
const config = resolveConfig({
type: 'stylesheet',
context: { name: 'align-content' }
});
equal(expand('s', config), 'start');
equal(expand('a', config), 'auto');
});
it('limit snippets by scope', () => {
const sectionScope = resolveConfig({
type: 'stylesheet',
context: { name: CSSAbbreviationScope.Section },
snippets: {
mten: 'margin: 10px;',
fsz: 'font-size',
myCenterAwesome: 'body {\n\tdisplay: grid;\n}'
}
});
const propertyScope = resolveConfig({
type: 'stylesheet',
context: { name: CSSAbbreviationScope.Property },
snippets: {
mten: 'margin: 10px;',
fsz: 'font-size',
myCenterAwesome: 'body {\n\tdisplay: grid;\n}'
}
});
equal(expand('m', sectionScope), 'body {\n\tdisplay: grid;\n}');
equal(expand('b', sectionScope), '');
equal(expand('m', propertyScope), 'margin: ;');
});
});
<MSG> Added CSS gradient resolver
<DFF> @@ -135,6 +135,11 @@ describe('Stylesheet abbreviations', () => {
equal(expand('trf:rx'), 'transform: rotateX(${1:angle});');
});
+ it('gradient resolver', () => {
+ equal(expand('lg'), 'background-image: linear-gradient(${0});');
+ equal(expand('lg(to right, #0, #f00.5)'), 'background-image: linear-gradient(to right, #000, rgba(255, 0, 0, 0.5));');
+ });
+
it('use min score when finding best match for snippets', () => {
equal(expand('auto', resolveConfig({ options: { 'stylesheet.fuzzySearchMinScore': 0 } })), 'align-self: unset;');
equal(expand('auto', resolveConfig({ options: { 'stylesheet.fuzzySearchMinScore': 0.3 } })), 'auto: ;');
| 5 | Added CSS gradient resolver | 0 | .ts | ts | mit | emmetio/emmet |
10071882 | <NME> stylesheet.ts
<BEF> import { strictEqual as equal, ok } from 'assert';
import { stylesheet as expandAbbreviation, resolveConfig, CSSAbbreviationScope } from '../src';
import score from '../src/stylesheet/score';
const defaultConfig = resolveConfig({
type: 'stylesheet',
options: {
'output.field': (index, placeholder) => `\${${index}${placeholder ? ':' + placeholder : ''}}`,
'stylesheet.fuzzySearchMinScore': 0
},
snippets: {
mten: 'margin: 10px;',
fsz: 'font-size',
gt: 'grid-template: repeat(2,auto) / repeat(auto-fit, minmax(250px, 1fr))'
},
cache: {},
});
function expand(abbr: string, config = defaultConfig) {
return expandAbbreviation(abbr, config);
}
describe('Stylesheet abbreviations', () => {
describe('Scoring', () => {
const pick = (abbr: string, items: string[]) => items
.map(item => ({ item, score: score(abbr, item, true) }))
.filter(obj => obj.score)
.sort((a, b) => b.score - a.score)
.map(obj => obj.item)[0];
it('compare scores', () => {
equal(score('aaa', 'aaa'), 1);
equal(score('baa', 'aaa'), 0);
ok(!score('b', 'aaa'));
ok(score('a', 'aaa'));
ok(score('a', 'abc'));
ok(score('ac', 'abc'));
ok(score('a', 'aaa') < score('aa', 'aaa'));
ok(score('ab', 'abc') > score('ab', 'acb'));
// acronym bonus
ok(score('ab', 'a-b') > score('ab', 'acb'));
});
it('pick padding or position', () => {
const items = ['p', 'pb', 'pl', 'pos', 'pa', 'oa', 'soa', 'pr', 'pt'];
equal(pick('p', items), 'p');
equal(pick('poa', items), 'pos');
});
});
it('keywords', () => {
equal(expand('bd1-s'), 'border: 1px solid;');
equal(expand('dib'), 'display: inline-block;');
equal(expand('bxsz'), 'box-sizing: ${1:border-box};');
equal(expand('bxz'), 'box-sizing: ${1:border-box};');
equal(expand('bxzc'), 'box-sizing: content-box;');
equal(expand('fl'), 'float: ${1:left};');
equal(expand('fll'), 'float: left;');
equal(expand('pos'), 'position: ${1:relative};');
equal(expand('poa'), 'position: absolute;');
equal(expand('por'), 'position: relative;');
equal(expand('pof'), 'position: fixed;');
equal(expand('pos-a'), 'position: absolute;');
equal(expand('m'), 'margin: ${0};');
equal(expand('m0'), 'margin: 0;');
// use `auto` as global keyword
equal(expand('m0-a'), 'margin: 0 auto;');
equal(expand('m-a'), 'margin: auto;');
equal(expand('bg'), 'background: ${1:#000};');
equal(expand('bd'), 'border: ${1:1px} ${2:solid} ${3:#000};');
equal(expand('bd0-s#fc0'), 'border: 0 solid #fc0;');
equal(expand('bd0-dd#fc0'), 'border: 0 dot-dash #fc0;');
equal(expand('bd0-h#fc0'), 'border: 0 hidden #fc0;');
equal(expand('trf-trs'), 'transform: translate(${1:x}, ${2:y});');
// https://github.com/emmetio/emmet/issues/610
equal(expand('c'), 'color: ${1:#000};');
equal(expand('cr'), 'color: rgb(${1:0}, ${2:0}, ${3:0});');
equal(expand('cra'), 'color: rgba(${1:0}, ${2:0}, ${3:0}, ${4:.5});');
// https://github.com/emmetio/emmet/issues/647
equal(expand('gtc'), 'grid-template-columns: repeat(${0});');
equal(expand('gtr'), 'grid-template-rows: repeat(${0});');
equal(expand('lis:n'), 'list-style: none;');
equal(expand('list:n'), 'list-style-type: none;');
equal(expand('bdt:n'), 'border-top: none;');
equal(expand('bgi:n'), 'background-image: none;');
equal(expand('q:n'), 'quotes: none;');
});
it('numeric', () => {
equal(expand('p0'), 'padding: 0;', 'No unit for 0');
equal(expand('p10'), 'padding: 10px;', '`px` unit for integers');
equal(expand('p.4'), 'padding: 0.4em;', '`em` for floats');
equal(expand('fz10'), 'font-size: 10px;', '`px` for integers');
equal(expand('fz1.'), 'font-size: 1em;', '`em` for explicit float');
equal(expand('p10p'), 'padding: 10%;', 'unit alias');
equal(expand('z10'), 'z-index: 10;', 'Unitless property');
equal(expand('p10r'), 'padding: 10rem;', 'unit alias');
equal(expand('mten'), 'margin: 10px;', 'Ignore terminating `;` in snippet');
// https://github.com/microsoft/vscode/issues/59951
equal(expand('fz'), 'font-size: ${0};');
equal(expand('fz12'), 'font-size: 12px;');
equal(expand('fsz'), 'font-size: ${0};');
equal(expand('fsz12'), 'font-size: 12px;');
equal(expand('fs'), 'font-style: ${1:italic};');
// https://github.com/emmetio/emmet/issues/558
equal(expand('us'), 'user-select: none;');
// https://github.com/microsoft/vscode/issues/105697
equal(expand('opa1'), 'opacity: 1;', 'Unitless property');
equal(expand('opa.1'), 'opacity: 0.1;', 'Unitless property');
equal(expand('opa.a'), 'opacity: .a;', 'Unitless property');
});
it('numeric with format options', () => {
const config = resolveConfig({
type: 'stylesheet',
options: {
'stylesheet.intUnit': 'pt',
'stylesheet.floatUnit': 'vh',
'stylesheet.unitAliases': {
equal(expand('trf:rx'), 'transform: rotateX(${1:angle});');
});
it('use min score when finding best match for snippets', () => {
equal(expand('auto', resolveConfig({ options: { 'stylesheet.fuzzySearchMinScore': 0 } })), 'align-self: unset;');
equal(expand('auto', resolveConfig({ options: { 'stylesheet.fuzzySearchMinScore': 0.3 } })), 'auto: ;');
equal(expand('z10', config), 'z-index: 10;', 'Unitless property');
equal(expand('p10r', config), 'padding: 10 / @rem;', 'unit alias');
});
it('important', () => {
equal(expand('!'), '!important');
equal(expand('p!'), 'padding: ${0} !important;');
equal(expand('p0!'), 'padding: 0 !important;');
});
it('color', () => {
equal(expand('c'), 'color: ${1:#000};');
equal(expand('c#'), 'color: #000;');
equal(expand('c#f.5'), 'color: rgba(255, 255, 255, 0.5);');
equal(expand('c#f.5!'), 'color: rgba(255, 255, 255, 0.5) !important;');
equal(expand('bgc'), 'background-color: #${1:fff};');
});
it('snippets', () => {
equal(expand('@'), '@media ${1:screen} {\n\t${0}\n}');
// Insert value into snippet fields
equal(expand('@k-name'), '@keyframes name {\n\t${2}\n}');
equal(expand('@k-name10'), '@keyframes name {\n\t10\n}');
equal(expand('gt'), 'grid-template: repeat(2, auto) / repeat(auto-fit, minmax(250px, 1fr));');
});
it('multiple properties', () => {
equal(expand('p10+m10-20'), 'padding: 10px;\nmargin: 10px 20px;');
equal(expand('p+bd'), 'padding: ${0};\nborder: ${1:1px} ${2:solid} ${3:#000};');
});
it('functions', () => {
equal(expand('trf-s(2)'), 'transform: scale(2, ${2:y});');
equal(expand('trf-s(2, 3)'), 'transform: scale(2, 3);');
});
it('case insensitive matches', () => {
equal(expand('trf:rx'), 'transform: rotateX(${1:angle});');
});
it('gradient resolver', () => {
equal(expand('lg'), 'background-image: linear-gradient(${0});');
equal(expand('lg(to right, #0, #f00.5)'), 'background-image: linear-gradient(to right, #000, rgba(255, 0, 0, 0.5));');
});
it('unmatched abbreviation', () => {
// This example is useless: it’s unexpected to receive `align-self: unset`
// for `auto` snippet
// equal(expand('auto', resolveConfig({
// type: 'stylesheet',
// options: { 'stylesheet.fuzzySearchMinScore': 0 }
// })), 'align-self: unset;');
equal(expand('auto'), 'auto: ${0};');
});
it('CSS-in-JS', () => {
const config = resolveConfig({
type: 'stylesheet',
options: {
'stylesheet.json': true,
'stylesheet.between': ': '
}
});
equal(expand('p10+mt10-20', config), 'padding: 10,\nmarginTop: \'10px 20px\',');
equal(expand('bgc', config), 'backgroundColor: \'#fff\',');
});
it('resolve context value', () => {
const config = resolveConfig({
type: 'stylesheet',
context: { name: 'align-content' }
});
equal(expand('s', config), 'start');
equal(expand('a', config), 'auto');
});
it('limit snippets by scope', () => {
const sectionScope = resolveConfig({
type: 'stylesheet',
context: { name: CSSAbbreviationScope.Section },
snippets: {
mten: 'margin: 10px;',
fsz: 'font-size',
myCenterAwesome: 'body {\n\tdisplay: grid;\n}'
}
});
const propertyScope = resolveConfig({
type: 'stylesheet',
context: { name: CSSAbbreviationScope.Property },
snippets: {
mten: 'margin: 10px;',
fsz: 'font-size',
myCenterAwesome: 'body {\n\tdisplay: grid;\n}'
}
});
equal(expand('m', sectionScope), 'body {\n\tdisplay: grid;\n}');
equal(expand('b', sectionScope), '');
equal(expand('m', propertyScope), 'margin: ;');
});
});
<MSG> Added CSS gradient resolver
<DFF> @@ -135,6 +135,11 @@ describe('Stylesheet abbreviations', () => {
equal(expand('trf:rx'), 'transform: rotateX(${1:angle});');
});
+ it('gradient resolver', () => {
+ equal(expand('lg'), 'background-image: linear-gradient(${0});');
+ equal(expand('lg(to right, #0, #f00.5)'), 'background-image: linear-gradient(to right, #000, rgba(255, 0, 0, 0.5));');
+ });
+
it('use min score when finding best match for snippets', () => {
equal(expand('auto', resolveConfig({ options: { 'stylesheet.fuzzySearchMinScore': 0 } })), 'align-self: unset;');
equal(expand('auto', resolveConfig({ options: { 'stylesheet.fuzzySearchMinScore': 0.3 } })), 'auto: ;');
| 5 | Added CSS gradient resolver | 0 | .ts | ts | mit | emmetio/emmet |
10071883 | <NME> experiment_spec.rb
<BEF> # frozen_string_literal: true
require "spec_helper"
require "time"
describe Split::Experiment do
def new_experiment(goals = [])
Split::Experiment.new("link_color", alternatives: ["blue", "red", "green"], goals: goals)
end
def alternative(color)
Split::Alternative.new(color, "link_color")
end
let(:experiment) { new_experiment }
let(:blue) { alternative("blue") }
let(:green) { alternative("green") }
context "with an experiment" do
let(:experiment) { Split::Experiment.new("basket_text", alternatives: ["Basket", "Cart"]) }
it "should have a name" do
expect(experiment.name).to eq("basket_text")
end
it "should have alternatives" do
expect(experiment.alternatives.length).to be 2
end
it "should have alternatives with correct names" do
expect(experiment.alternatives.collect { |a| a.name }).to eq(["Basket", "Cart"])
end
it "should be resettable by default" do
expect(experiment.resettable).to be_truthy
end
it "should save to redis" do
experiment.save
expect(Split.redis.exists?("basket_text")).to be true
end
it "should save the start time to redis" do
experiment_start_time = Time.at(1372167761)
expect(Time).to receive(:now).and_return(experiment_start_time)
experiment.save
expect(Split::ExperimentCatalog.find("basket_text").start_time).to eq(experiment_start_time)
end
it "should not save the start time to redis when start_manually is enabled" do
expect(Split.configuration).to receive(:start_manually).and_return(true)
experiment.save
expect(Split::ExperimentCatalog.find("basket_text").start_time).to be_nil
end
it "should save the selected algorithm to redis" do
experiment_algorithm = Split::Algorithms::Whiplash
experiment.algorithm = experiment_algorithm
experiment.save
expect(Split::ExperimentCatalog.find("basket_text").algorithm).to eq(experiment_algorithm)
end
it "should handle having a start time stored as a string" do
experiment_start_time = Time.parse("Sat Mar 03 14:01:03")
expect(Time).to receive(:now).twice.and_return(experiment_start_time)
experiment.save
Split.redis.hset(:experiment_start_times, experiment.name, experiment_start_time.to_s)
expect(Split::ExperimentCatalog.find("basket_text").start_time).to eq(experiment_start_time)
end
it "should handle not having a start time" do
experiment_start_time = Time.parse("Sat Mar 03 14:01:03")
expect(Time).to receive(:now).and_return(experiment_start_time)
experiment.save
Split.redis.hdel(:experiment_start_times, experiment.name)
expect(Split::ExperimentCatalog.find("basket_text").start_time).to be_nil
end
it "should not create duplicates when saving multiple times" do
experiment.save
experiment.save
expect(Split.redis.exists?("basket_text")).to be true
expect(Split.redis.lrange("basket_text", 0, -1)).to eq(['{"Basket":1}', '{"Cart":1}'])
end
describe "new record?" do
it "should know if it hasn't been saved yet" do
expect(experiment.new_record?).to be_truthy
end
it "should know if it has been saved yet" do
experiment.save
expect(experiment.new_record?).to be_falsey
end
end
describe "control" do
it "should be the first alternative" do
experiment.save
expect(experiment.control.name).to eq("Basket")
end
end
end
describe "initialization" do
it "should set the algorithm when passed as an option to the initializer" do
experiment = Split::Experiment.new("basket_text", alternatives: ["Basket", "Cart"], algorithm: Split::Algorithms::Whiplash)
expect(experiment.algorithm).to eq(Split::Algorithms::Whiplash)
end
it "should be possible to make an experiment not resettable" do
experiment = Split::Experiment.new("basket_text", alternatives: ["Basket", "Cart"], resettable: false)
expect(experiment.resettable).to be_falsey
end
context "from configuration" do
let(:experiment_name) { :my_experiment }
let(:experiments) do
{
experiment_name => {
alternatives: ["Control Opt", "Alt one"]
}
}
end
before { Split.configuration.experiments = experiments }
it "assigns default values to the experiment" do
expect(Split::Experiment.new(experiment_name).resettable).to eq(true)
end
end
end
describe "persistent configuration" do
it "should persist resettable in redis" do
experiment = Split::Experiment.new("basket_text", alternatives: ["Basket", "Cart"], resettable: false)
experiment.save
e = Split::ExperimentCatalog.find("basket_text")
expect(e).to eq(experiment)
expect(e.resettable).to be_falsey
end
describe "#metadata" do
let(:experiment) { Split::Experiment.new("basket_text", alternatives: ["Basket", "Cart"], algorithm: Split::Algorithms::Whiplash, metadata: meta) }
let(:meta) { { a: "b" } }
before do
experiment.save
end
it "should delete the key when metadata is removed" do
experiment.metadata = nil
experiment.save
expect(Split.redis.exists?(experiment.metadata_key)).to be_falsey
end
context "simple hash" do
let(:meta) { { "basket" => "a", "cart" => "b" } }
it "should persist metadata in redis" do
e = Split::ExperimentCatalog.find("basket_text")
expect(e).to eq(experiment)
expect(e.metadata).to eq(meta)
end
end
context "nested hash" do
let(:meta) { { "basket" => { "one" => "two" }, "cart" => "b" } }
it "should persist metadata in redis" do
e = Split::ExperimentCatalog.find("basket_text")
expect(e).to eq(experiment)
expect(e.metadata).to eq(meta)
end
end
end
it "should persist algorithm in redis" do
experiment = Split::Experiment.new("basket_text", alternatives: ["Basket", "Cart"], algorithm: Split::Algorithms::Whiplash)
experiment.save
e = Split::ExperimentCatalog.find("basket_text")
expect(e).to eq(experiment)
expect(e.algorithm).to eq(Split::Algorithms::Whiplash)
end
it "should persist a new experiment in redis, that does not exist in the configuration file" do
experiment = Split::Experiment.new("foobar", alternatives: ["tra", "la"], algorithm: Split::Algorithms::Whiplash)
experiment.save
e = Split::ExperimentCatalog.find("foobar")
expect(e).to eq(experiment)
expect(e.alternatives.collect { |a| a.name }).to eq(["tra", "la"])
end
end
describe "deleting" do
it "should delete itself" do
experiment = Split::Experiment.new("basket_text", alternatives: [ "Basket", "Cart"])
experiment.save
experiment.delete
expect(Split.redis.exists?("link_color")).to be false
expect(Split::ExperimentCatalog.find("link_color")).to be_nil
end
it "should increment the version" do
expect(experiment.version).to eq(0)
experiment.delete
expect(experiment.version).to eq(1)
end
it "should call the on_experiment_delete hook" do
expect(Split.configuration.on_experiment_delete).to receive(:call)
experiment.delete
end
it "should call the on_before_experiment_delete hook" do
expect(Split.configuration.on_before_experiment_delete).to receive(:call)
experiment.delete
end
it "should reset the start time if the experiment should be manually started" do
Split.configuration.start_manually = true
experiment.start
experiment.delete
expect(experiment.start_time).to be_nil
end
it "should default cohorting back to false" do
experiment.disable_cohorting
expect(experiment.cohorting_disabled?).to eq(true)
experiment.delete
expect(experiment.cohorting_disabled?).to eq(false)
end
end
describe "winner" do
it "should have no winner initially" do
expect(experiment.winner).to be_nil
end
end
describe "winner=" do
it "should allow you to specify a winner" do
experiment.save
experiment.winner = "red"
expect(experiment.winner.name).to eq("red")
end
it "should call the on_experiment_winner_choose hook" do
expect(Split.configuration.on_experiment_winner_choose).to receive(:call)
experiment.winner = "green"
end
context "when has_winner state is memoized" do
before { expect(experiment).to_not have_winner }
it "should keep has_winner state consistent" do
experiment.winner = "red"
expect(experiment).to have_winner
end
end
end
describe "reset_winner" do
before { experiment.winner = "green" }
it "should reset the winner" do
experiment.reset_winner
expect(experiment.winner).to be_nil
end
context "when has_winner state is memoized" do
before { expect(experiment).to have_winner }
it "should keep has_winner state consistent" do
experiment.reset_winner
expect(experiment).to_not have_winner
end
end
end
describe "has_winner?" do
context "with winner" do
before { experiment.winner = "red" }
it "returns true" do
expect(experiment).to have_winner
end
end
context "without winner" do
it "returns false" do
expect(experiment).to_not have_winner
end
end
it "memoizes has_winner state" do
expect(experiment).to receive(:winner).once
expect(experiment).to_not have_winner
expect(experiment).to_not have_winner
end
end
describe "reset" do
let(:reset_manually) { false }
before do
allow(Split.configuration).to receive(:reset_manually).and_return(reset_manually)
experiment.save
green.increment_participation
green.increment_participation
end
it "should reset all alternatives" do
experiment.winner = "green"
expect(experiment.next_alternative.name).to eq("green")
green.increment_participation
experiment.reset
expect(green.participant_count).to eq(0)
expect(green.completed_count).to eq(0)
end
it "should reset the winner" do
experiment.winner = "green"
expect(experiment.next_alternative.name).to eq("green")
green.increment_participation
experiment.reset
expect(experiment.winner).to be_nil
end
it "should increment the version" do
expect(experiment.version).to eq(0)
experiment.reset
expect(experiment.version).to eq(1)
end
it "should call the on_experiment_reset hook" do
expect(Split.configuration.on_experiment_reset).to receive(:call)
experiment.reset
end
it "should call the on_before_experiment_reset hook" do
expect(Split.configuration.on_before_experiment_reset).to receive(:call)
experiment.reset
end
end
describe "algorithm" do
let(:experiment) { Split::ExperimentCatalog.find_or_create("link_color", "blue", "red", "green") }
it "should use the default algorithm if none is specified" do
expect(experiment.algorithm).to eq(Split.configuration.algorithm)
end
it "should use the user specified algorithm for this experiment if specified" do
experiment.algorithm = Split::Algorithms::Whiplash
expect(experiment.algorithm).to eq(Split::Algorithms::Whiplash)
end
end
end
end
end
describe "#cohorting_disabled?" do
it "returns false when nothing has been configured" do
expect(experiment.cohorting_disabled?).to eq false
end
it "returns true when enable_cohorting is performed" do
experiment.enable_cohorting
expect(experiment.cohorting_disabled?).to eq false
end
it "returns false when nothing has been configured" do
experiment.disable_cohorting
expect(experiment.cohorting_disabled?).to eq true
end
end
describe "changing an existing experiment" do
def same_but_different_alternative
Split::ExperimentCatalog.find_or_create("link_color", "blue", "yellow", "orange")
end
it "should reset an experiment if it is loaded with different alternatives" do
experiment.save
blue.participant_count = 5
same_experiment = same_but_different_alternative
expect(same_experiment.alternatives.map(&:name)).to eq(["blue", "yellow", "orange"])
expect(blue.participant_count).to eq(0)
end
it "should only reset once" do
experiment.save
expect(experiment.version).to eq(0)
same_experiment = same_but_different_alternative
expect(same_experiment.version).to eq(1)
same_experiment_again = same_but_different_alternative
expect(same_experiment_again.version).to eq(1)
end
context "when metadata is changed" do
it "should increase version" do
experiment.save
experiment.metadata = { "foo" => "bar" }
expect { experiment.save }.to change { experiment.version }.by(1)
end
it "does not increase version" do
experiment.metadata = nil
experiment.save
expect { experiment.save }.to change { experiment.version }.by(0)
end
end
context "when experiment configuration is changed" do
let(:reset_manually) { false }
before do
experiment.save
allow(Split.configuration).to receive(:reset_manually).and_return(reset_manually)
green.increment_participation
green.increment_participation
experiment.set_alternatives_and_options(alternatives: %w(blue red green zip),
goals: %w(purchase))
experiment.save
end
it "resets all alternatives" do
expect(green.participant_count).to eq(0)
expect(green.completed_count).to eq(0)
end
context "when reset_manually is set" do
let(:reset_manually) { true }
it "does not reset alternatives" do
expect(green.participant_count).to eq(2)
expect(green.completed_count).to eq(0)
end
end
end
end
describe "alternatives passed as non-strings" do
it "should throw an exception if an alternative is passed that is not a string" do
expect { Split::ExperimentCatalog.find_or_create("link_color", :blue, :red) }.to raise_error(ArgumentError)
expect { Split::ExperimentCatalog.find_or_create("link_enabled", true, false) }.to raise_error(ArgumentError)
end
end
describe "specifying weights" do
let(:experiment_with_weight) {
Split::ExperimentCatalog.find_or_create("link_color", { "blue" => 1 }, { "red" => 2 })
}
it "should work for a new experiment" do
expect(experiment_with_weight.alternatives.map(&:weight)).to eq([1, 2])
end
it "should work for an existing experiment" do
experiment.save
expect(experiment_with_weight.alternatives.map(&:weight)).to eq([1, 2])
end
end
describe "specifying goals" do
let(:experiment) {
new_experiment(["purchase"])
}
context "saving experiment" do
let(:same_but_different_goals) { Split::ExperimentCatalog.find_or_create({ "link_color" => ["purchase", "refund"] }, "blue", "red", "green") }
before { experiment.save }
it "can find existing experiment" do
expect(Split::ExperimentCatalog.find("link_color").name).to eq("link_color")
end
it "should reset an experiment if it is loaded with different goals" do
same_but_different_goals
expect(Split::ExperimentCatalog.find("link_color").goals).to eq(["purchase", "refund"])
end
end
it "should have goals" do
expect(experiment.goals).to eq(["purchase"])
end
context "find or create experiment" do
it "should have correct goals" do
experiment = Split::ExperimentCatalog.find_or_create({ "link_color3" => ["purchase", "refund"] }, "blue", "red", "green")
expect(experiment.goals).to eq(["purchase", "refund"])
experiment = Split::ExperimentCatalog.find_or_create("link_color3", "blue", "red", "green")
expect(experiment.goals).to eq([])
end
end
end
describe "beta probability calculation" do
it "should return a hash with the probability of each alternative being the best" do
experiment = Split::ExperimentCatalog.find_or_create("mathematicians", "bernoulli", "poisson", "lagrange")
experiment.calc_winning_alternatives
expect(experiment.alternative_probabilities).not_to be_nil
end
it "should return between 46% and 54% probability for an experiment with 2 alternatives and no data" do
experiment = Split::ExperimentCatalog.find_or_create("scientists", "einstein", "bohr")
experiment.calc_winning_alternatives
expect(experiment.alternatives[0].p_winner).to be_within(0.04).of(0.50)
end
it "should calculate the probability of being the winning alternative separately for each goal", skip: true do
experiment = Split::ExperimentCatalog.find_or_create({ "link_color3" => ["purchase", "refund"] }, "blue", "red", "green")
goal1 = experiment.goals[0]
goal2 = experiment.goals[1]
experiment.alternatives.each do |alternative|
alternative.participant_count = 50
alternative.set_completed_count(10, goal1)
alternative.set_completed_count(15+rand(30), goal2)
end
experiment.calc_winning_alternatives
alt = experiment.alternatives[0]
p_goal1 = alt.p_winner(goal1)
p_goal2 = alt.p_winner(goal2)
expect(p_goal1).not_to be_within(0.04).of(p_goal2)
end
it "should return nil and not re-calculate probabilities if they have already been calculated today" do
experiment = Split::ExperimentCatalog.find_or_create({ "link_color3" => ["purchase", "refund"] }, "blue", "red", "green")
expect(experiment.calc_winning_alternatives).not_to be nil
expect(experiment.calc_winning_alternatives).to be nil
end
end
end
<MSG> Adds functionality which uses the beta distribution to calculate the probability an alternative is the winner. Necessary for comparing more than 2 alternatives.
<DFF> @@ -377,4 +377,34 @@ describe Split::Experiment do
end
end
+ describe "beta probability calculation" do
+ it "should return a hash with the probability of each alternative being the best" do
+ experiment = Split::Experiment.find_or_create('mathematicians', 'bernoulli', 'poisson', 'lagrange')
+ experiment.calc_winning_alternatives
+ experiment.alternative_probabilities.should_not be_nil
+ end
+
+ it "should return between 46% and 54% probability for an experiment with 2 alternatives and no data" do
+ experiment = Split::Experiment.find_or_create('scientists', 'einstein', 'bohr')
+ experiment.calc_winning_alternatives
+ experiment.alternatives[0].p_winner.should be_within(0.04).of(0.50)
+ end
+
+ it "should calculate the probability of being the winning alternative separately for each goal" do
+ experiment = Split::Experiment.find_or_create({'link_color3' => ["purchase", "refund"]}, 'blue', 'red', 'green')
+ goal1 = experiment.goals[0]
+ goal2 = experiment.goals[1]
+ experiment.alternatives.each do |alternative|
+ alternative.participant_count = 50
+ alternative.set_completed_count(10, goal1)
+ alternative.set_completed_count(10+rand(30), goal2)
+ end
+ experiment.calc_winning_alternatives
+ alt = experiment.alternatives[0]
+ p_goal1 = alt.p_winner(goal1)
+ p_goal2 = alt.p_winner(goal2)
+ p_goal1.should_not be_within(0.04).of(p_goal2)
+ end
+ end
+
end
| 30 | Adds functionality which uses the beta distribution to calculate the probability an alternative is the winner. Necessary for comparing more than 2 alternatives. | 0 | .rb | rb | mit | splitrb/split |
10071884 | <NME> experiment_spec.rb
<BEF> # frozen_string_literal: true
require "spec_helper"
require "time"
describe Split::Experiment do
def new_experiment(goals = [])
Split::Experiment.new("link_color", alternatives: ["blue", "red", "green"], goals: goals)
end
def alternative(color)
Split::Alternative.new(color, "link_color")
end
let(:experiment) { new_experiment }
let(:blue) { alternative("blue") }
let(:green) { alternative("green") }
context "with an experiment" do
let(:experiment) { Split::Experiment.new("basket_text", alternatives: ["Basket", "Cart"]) }
it "should have a name" do
expect(experiment.name).to eq("basket_text")
end
it "should have alternatives" do
expect(experiment.alternatives.length).to be 2
end
it "should have alternatives with correct names" do
expect(experiment.alternatives.collect { |a| a.name }).to eq(["Basket", "Cart"])
end
it "should be resettable by default" do
expect(experiment.resettable).to be_truthy
end
it "should save to redis" do
experiment.save
expect(Split.redis.exists?("basket_text")).to be true
end
it "should save the start time to redis" do
experiment_start_time = Time.at(1372167761)
expect(Time).to receive(:now).and_return(experiment_start_time)
experiment.save
expect(Split::ExperimentCatalog.find("basket_text").start_time).to eq(experiment_start_time)
end
it "should not save the start time to redis when start_manually is enabled" do
expect(Split.configuration).to receive(:start_manually).and_return(true)
experiment.save
expect(Split::ExperimentCatalog.find("basket_text").start_time).to be_nil
end
it "should save the selected algorithm to redis" do
experiment_algorithm = Split::Algorithms::Whiplash
experiment.algorithm = experiment_algorithm
experiment.save
expect(Split::ExperimentCatalog.find("basket_text").algorithm).to eq(experiment_algorithm)
end
it "should handle having a start time stored as a string" do
experiment_start_time = Time.parse("Sat Mar 03 14:01:03")
expect(Time).to receive(:now).twice.and_return(experiment_start_time)
experiment.save
Split.redis.hset(:experiment_start_times, experiment.name, experiment_start_time.to_s)
expect(Split::ExperimentCatalog.find("basket_text").start_time).to eq(experiment_start_time)
end
it "should handle not having a start time" do
experiment_start_time = Time.parse("Sat Mar 03 14:01:03")
expect(Time).to receive(:now).and_return(experiment_start_time)
experiment.save
Split.redis.hdel(:experiment_start_times, experiment.name)
expect(Split::ExperimentCatalog.find("basket_text").start_time).to be_nil
end
it "should not create duplicates when saving multiple times" do
experiment.save
experiment.save
expect(Split.redis.exists?("basket_text")).to be true
expect(Split.redis.lrange("basket_text", 0, -1)).to eq(['{"Basket":1}', '{"Cart":1}'])
end
describe "new record?" do
it "should know if it hasn't been saved yet" do
expect(experiment.new_record?).to be_truthy
end
it "should know if it has been saved yet" do
experiment.save
expect(experiment.new_record?).to be_falsey
end
end
describe "control" do
it "should be the first alternative" do
experiment.save
expect(experiment.control.name).to eq("Basket")
end
end
end
describe "initialization" do
it "should set the algorithm when passed as an option to the initializer" do
experiment = Split::Experiment.new("basket_text", alternatives: ["Basket", "Cart"], algorithm: Split::Algorithms::Whiplash)
expect(experiment.algorithm).to eq(Split::Algorithms::Whiplash)
end
it "should be possible to make an experiment not resettable" do
experiment = Split::Experiment.new("basket_text", alternatives: ["Basket", "Cart"], resettable: false)
expect(experiment.resettable).to be_falsey
end
context "from configuration" do
let(:experiment_name) { :my_experiment }
let(:experiments) do
{
experiment_name => {
alternatives: ["Control Opt", "Alt one"]
}
}
end
before { Split.configuration.experiments = experiments }
it "assigns default values to the experiment" do
expect(Split::Experiment.new(experiment_name).resettable).to eq(true)
end
end
end
describe "persistent configuration" do
it "should persist resettable in redis" do
experiment = Split::Experiment.new("basket_text", alternatives: ["Basket", "Cart"], resettable: false)
experiment.save
e = Split::ExperimentCatalog.find("basket_text")
expect(e).to eq(experiment)
expect(e.resettable).to be_falsey
end
describe "#metadata" do
let(:experiment) { Split::Experiment.new("basket_text", alternatives: ["Basket", "Cart"], algorithm: Split::Algorithms::Whiplash, metadata: meta) }
let(:meta) { { a: "b" } }
before do
experiment.save
end
it "should delete the key when metadata is removed" do
experiment.metadata = nil
experiment.save
expect(Split.redis.exists?(experiment.metadata_key)).to be_falsey
end
context "simple hash" do
let(:meta) { { "basket" => "a", "cart" => "b" } }
it "should persist metadata in redis" do
e = Split::ExperimentCatalog.find("basket_text")
expect(e).to eq(experiment)
expect(e.metadata).to eq(meta)
end
end
context "nested hash" do
let(:meta) { { "basket" => { "one" => "two" }, "cart" => "b" } }
it "should persist metadata in redis" do
e = Split::ExperimentCatalog.find("basket_text")
expect(e).to eq(experiment)
expect(e.metadata).to eq(meta)
end
end
end
it "should persist algorithm in redis" do
experiment = Split::Experiment.new("basket_text", alternatives: ["Basket", "Cart"], algorithm: Split::Algorithms::Whiplash)
experiment.save
e = Split::ExperimentCatalog.find("basket_text")
expect(e).to eq(experiment)
expect(e.algorithm).to eq(Split::Algorithms::Whiplash)
end
it "should persist a new experiment in redis, that does not exist in the configuration file" do
experiment = Split::Experiment.new("foobar", alternatives: ["tra", "la"], algorithm: Split::Algorithms::Whiplash)
experiment.save
e = Split::ExperimentCatalog.find("foobar")
expect(e).to eq(experiment)
expect(e.alternatives.collect { |a| a.name }).to eq(["tra", "la"])
end
end
describe "deleting" do
it "should delete itself" do
experiment = Split::Experiment.new("basket_text", alternatives: [ "Basket", "Cart"])
experiment.save
experiment.delete
expect(Split.redis.exists?("link_color")).to be false
expect(Split::ExperimentCatalog.find("link_color")).to be_nil
end
it "should increment the version" do
expect(experiment.version).to eq(0)
experiment.delete
expect(experiment.version).to eq(1)
end
it "should call the on_experiment_delete hook" do
expect(Split.configuration.on_experiment_delete).to receive(:call)
experiment.delete
end
it "should call the on_before_experiment_delete hook" do
expect(Split.configuration.on_before_experiment_delete).to receive(:call)
experiment.delete
end
it "should reset the start time if the experiment should be manually started" do
Split.configuration.start_manually = true
experiment.start
experiment.delete
expect(experiment.start_time).to be_nil
end
it "should default cohorting back to false" do
experiment.disable_cohorting
expect(experiment.cohorting_disabled?).to eq(true)
experiment.delete
expect(experiment.cohorting_disabled?).to eq(false)
end
end
describe "winner" do
it "should have no winner initially" do
expect(experiment.winner).to be_nil
end
end
describe "winner=" do
it "should allow you to specify a winner" do
experiment.save
experiment.winner = "red"
expect(experiment.winner.name).to eq("red")
end
it "should call the on_experiment_winner_choose hook" do
expect(Split.configuration.on_experiment_winner_choose).to receive(:call)
experiment.winner = "green"
end
context "when has_winner state is memoized" do
before { expect(experiment).to_not have_winner }
it "should keep has_winner state consistent" do
experiment.winner = "red"
expect(experiment).to have_winner
end
end
end
describe "reset_winner" do
before { experiment.winner = "green" }
it "should reset the winner" do
experiment.reset_winner
expect(experiment.winner).to be_nil
end
context "when has_winner state is memoized" do
before { expect(experiment).to have_winner }
it "should keep has_winner state consistent" do
experiment.reset_winner
expect(experiment).to_not have_winner
end
end
end
describe "has_winner?" do
context "with winner" do
before { experiment.winner = "red" }
it "returns true" do
expect(experiment).to have_winner
end
end
context "without winner" do
it "returns false" do
expect(experiment).to_not have_winner
end
end
it "memoizes has_winner state" do
expect(experiment).to receive(:winner).once
expect(experiment).to_not have_winner
expect(experiment).to_not have_winner
end
end
describe "reset" do
let(:reset_manually) { false }
before do
allow(Split.configuration).to receive(:reset_manually).and_return(reset_manually)
experiment.save
green.increment_participation
green.increment_participation
end
it "should reset all alternatives" do
experiment.winner = "green"
expect(experiment.next_alternative.name).to eq("green")
green.increment_participation
experiment.reset
expect(green.participant_count).to eq(0)
expect(green.completed_count).to eq(0)
end
it "should reset the winner" do
experiment.winner = "green"
expect(experiment.next_alternative.name).to eq("green")
green.increment_participation
experiment.reset
expect(experiment.winner).to be_nil
end
it "should increment the version" do
expect(experiment.version).to eq(0)
experiment.reset
expect(experiment.version).to eq(1)
end
it "should call the on_experiment_reset hook" do
expect(Split.configuration.on_experiment_reset).to receive(:call)
experiment.reset
end
it "should call the on_before_experiment_reset hook" do
expect(Split.configuration.on_before_experiment_reset).to receive(:call)
experiment.reset
end
end
describe "algorithm" do
let(:experiment) { Split::ExperimentCatalog.find_or_create("link_color", "blue", "red", "green") }
it "should use the default algorithm if none is specified" do
expect(experiment.algorithm).to eq(Split.configuration.algorithm)
end
it "should use the user specified algorithm for this experiment if specified" do
experiment.algorithm = Split::Algorithms::Whiplash
expect(experiment.algorithm).to eq(Split::Algorithms::Whiplash)
end
end
end
end
end
describe "#cohorting_disabled?" do
it "returns false when nothing has been configured" do
expect(experiment.cohorting_disabled?).to eq false
end
it "returns true when enable_cohorting is performed" do
experiment.enable_cohorting
expect(experiment.cohorting_disabled?).to eq false
end
it "returns false when nothing has been configured" do
experiment.disable_cohorting
expect(experiment.cohorting_disabled?).to eq true
end
end
describe "changing an existing experiment" do
def same_but_different_alternative
Split::ExperimentCatalog.find_or_create("link_color", "blue", "yellow", "orange")
end
it "should reset an experiment if it is loaded with different alternatives" do
experiment.save
blue.participant_count = 5
same_experiment = same_but_different_alternative
expect(same_experiment.alternatives.map(&:name)).to eq(["blue", "yellow", "orange"])
expect(blue.participant_count).to eq(0)
end
it "should only reset once" do
experiment.save
expect(experiment.version).to eq(0)
same_experiment = same_but_different_alternative
expect(same_experiment.version).to eq(1)
same_experiment_again = same_but_different_alternative
expect(same_experiment_again.version).to eq(1)
end
context "when metadata is changed" do
it "should increase version" do
experiment.save
experiment.metadata = { "foo" => "bar" }
expect { experiment.save }.to change { experiment.version }.by(1)
end
it "does not increase version" do
experiment.metadata = nil
experiment.save
expect { experiment.save }.to change { experiment.version }.by(0)
end
end
context "when experiment configuration is changed" do
let(:reset_manually) { false }
before do
experiment.save
allow(Split.configuration).to receive(:reset_manually).and_return(reset_manually)
green.increment_participation
green.increment_participation
experiment.set_alternatives_and_options(alternatives: %w(blue red green zip),
goals: %w(purchase))
experiment.save
end
it "resets all alternatives" do
expect(green.participant_count).to eq(0)
expect(green.completed_count).to eq(0)
end
context "when reset_manually is set" do
let(:reset_manually) { true }
it "does not reset alternatives" do
expect(green.participant_count).to eq(2)
expect(green.completed_count).to eq(0)
end
end
end
end
describe "alternatives passed as non-strings" do
it "should throw an exception if an alternative is passed that is not a string" do
expect { Split::ExperimentCatalog.find_or_create("link_color", :blue, :red) }.to raise_error(ArgumentError)
expect { Split::ExperimentCatalog.find_or_create("link_enabled", true, false) }.to raise_error(ArgumentError)
end
end
describe "specifying weights" do
let(:experiment_with_weight) {
Split::ExperimentCatalog.find_or_create("link_color", { "blue" => 1 }, { "red" => 2 })
}
it "should work for a new experiment" do
expect(experiment_with_weight.alternatives.map(&:weight)).to eq([1, 2])
end
it "should work for an existing experiment" do
experiment.save
expect(experiment_with_weight.alternatives.map(&:weight)).to eq([1, 2])
end
end
describe "specifying goals" do
let(:experiment) {
new_experiment(["purchase"])
}
context "saving experiment" do
let(:same_but_different_goals) { Split::ExperimentCatalog.find_or_create({ "link_color" => ["purchase", "refund"] }, "blue", "red", "green") }
before { experiment.save }
it "can find existing experiment" do
expect(Split::ExperimentCatalog.find("link_color").name).to eq("link_color")
end
it "should reset an experiment if it is loaded with different goals" do
same_but_different_goals
expect(Split::ExperimentCatalog.find("link_color").goals).to eq(["purchase", "refund"])
end
end
it "should have goals" do
expect(experiment.goals).to eq(["purchase"])
end
context "find or create experiment" do
it "should have correct goals" do
experiment = Split::ExperimentCatalog.find_or_create({ "link_color3" => ["purchase", "refund"] }, "blue", "red", "green")
expect(experiment.goals).to eq(["purchase", "refund"])
experiment = Split::ExperimentCatalog.find_or_create("link_color3", "blue", "red", "green")
expect(experiment.goals).to eq([])
end
end
end
describe "beta probability calculation" do
it "should return a hash with the probability of each alternative being the best" do
experiment = Split::ExperimentCatalog.find_or_create("mathematicians", "bernoulli", "poisson", "lagrange")
experiment.calc_winning_alternatives
expect(experiment.alternative_probabilities).not_to be_nil
end
it "should return between 46% and 54% probability for an experiment with 2 alternatives and no data" do
experiment = Split::ExperimentCatalog.find_or_create("scientists", "einstein", "bohr")
experiment.calc_winning_alternatives
expect(experiment.alternatives[0].p_winner).to be_within(0.04).of(0.50)
end
it "should calculate the probability of being the winning alternative separately for each goal", skip: true do
experiment = Split::ExperimentCatalog.find_or_create({ "link_color3" => ["purchase", "refund"] }, "blue", "red", "green")
goal1 = experiment.goals[0]
goal2 = experiment.goals[1]
experiment.alternatives.each do |alternative|
alternative.participant_count = 50
alternative.set_completed_count(10, goal1)
alternative.set_completed_count(15+rand(30), goal2)
end
experiment.calc_winning_alternatives
alt = experiment.alternatives[0]
p_goal1 = alt.p_winner(goal1)
p_goal2 = alt.p_winner(goal2)
expect(p_goal1).not_to be_within(0.04).of(p_goal2)
end
it "should return nil and not re-calculate probabilities if they have already been calculated today" do
experiment = Split::ExperimentCatalog.find_or_create({ "link_color3" => ["purchase", "refund"] }, "blue", "red", "green")
expect(experiment.calc_winning_alternatives).not_to be nil
expect(experiment.calc_winning_alternatives).to be nil
end
end
end
<MSG> Adds functionality which uses the beta distribution to calculate the probability an alternative is the winner. Necessary for comparing more than 2 alternatives.
<DFF> @@ -377,4 +377,34 @@ describe Split::Experiment do
end
end
+ describe "beta probability calculation" do
+ it "should return a hash with the probability of each alternative being the best" do
+ experiment = Split::Experiment.find_or_create('mathematicians', 'bernoulli', 'poisson', 'lagrange')
+ experiment.calc_winning_alternatives
+ experiment.alternative_probabilities.should_not be_nil
+ end
+
+ it "should return between 46% and 54% probability for an experiment with 2 alternatives and no data" do
+ experiment = Split::Experiment.find_or_create('scientists', 'einstein', 'bohr')
+ experiment.calc_winning_alternatives
+ experiment.alternatives[0].p_winner.should be_within(0.04).of(0.50)
+ end
+
+ it "should calculate the probability of being the winning alternative separately for each goal" do
+ experiment = Split::Experiment.find_or_create({'link_color3' => ["purchase", "refund"]}, 'blue', 'red', 'green')
+ goal1 = experiment.goals[0]
+ goal2 = experiment.goals[1]
+ experiment.alternatives.each do |alternative|
+ alternative.participant_count = 50
+ alternative.set_completed_count(10, goal1)
+ alternative.set_completed_count(10+rand(30), goal2)
+ end
+ experiment.calc_winning_alternatives
+ alt = experiment.alternatives[0]
+ p_goal1 = alt.p_winner(goal1)
+ p_goal2 = alt.p_winner(goal2)
+ p_goal1.should_not be_within(0.04).of(p_goal2)
+ end
+ end
+
end
| 30 | Adds functionality which uses the beta distribution to calculate the probability an alternative is the winner. Necessary for comparing more than 2 alternatives. | 0 | .rb | rb | mit | splitrb/split |
10071885 | <NME> experiment_spec.rb
<BEF> # frozen_string_literal: true
require "spec_helper"
require "time"
describe Split::Experiment do
def new_experiment(goals = [])
Split::Experiment.new("link_color", alternatives: ["blue", "red", "green"], goals: goals)
end
def alternative(color)
Split::Alternative.new(color, "link_color")
end
let(:experiment) { new_experiment }
let(:blue) { alternative("blue") }
let(:green) { alternative("green") }
context "with an experiment" do
let(:experiment) { Split::Experiment.new("basket_text", alternatives: ["Basket", "Cart"]) }
it "should have a name" do
expect(experiment.name).to eq("basket_text")
end
it "should have alternatives" do
expect(experiment.alternatives.length).to be 2
end
it "should have alternatives with correct names" do
expect(experiment.alternatives.collect { |a| a.name }).to eq(["Basket", "Cart"])
end
it "should be resettable by default" do
expect(experiment.resettable).to be_truthy
end
it "should save to redis" do
experiment.save
expect(Split.redis.exists?("basket_text")).to be true
end
it "should save the start time to redis" do
experiment_start_time = Time.at(1372167761)
expect(Time).to receive(:now).and_return(experiment_start_time)
experiment.save
expect(Split::ExperimentCatalog.find("basket_text").start_time).to eq(experiment_start_time)
end
it "should not save the start time to redis when start_manually is enabled" do
expect(Split.configuration).to receive(:start_manually).and_return(true)
experiment.save
expect(Split::ExperimentCatalog.find("basket_text").start_time).to be_nil
end
it "should save the selected algorithm to redis" do
experiment_algorithm = Split::Algorithms::Whiplash
experiment.algorithm = experiment_algorithm
experiment.save
expect(Split::ExperimentCatalog.find("basket_text").algorithm).to eq(experiment_algorithm)
end
it "should handle having a start time stored as a string" do
experiment_start_time = Time.parse("Sat Mar 03 14:01:03")
expect(Time).to receive(:now).twice.and_return(experiment_start_time)
experiment.save
Split.redis.hset(:experiment_start_times, experiment.name, experiment_start_time.to_s)
expect(Split::ExperimentCatalog.find("basket_text").start_time).to eq(experiment_start_time)
end
it "should handle not having a start time" do
experiment_start_time = Time.parse("Sat Mar 03 14:01:03")
expect(Time).to receive(:now).and_return(experiment_start_time)
experiment.save
Split.redis.hdel(:experiment_start_times, experiment.name)
expect(Split::ExperimentCatalog.find("basket_text").start_time).to be_nil
end
it "should not create duplicates when saving multiple times" do
experiment.save
experiment.save
expect(Split.redis.exists?("basket_text")).to be true
expect(Split.redis.lrange("basket_text", 0, -1)).to eq(['{"Basket":1}', '{"Cart":1}'])
end
describe "new record?" do
it "should know if it hasn't been saved yet" do
expect(experiment.new_record?).to be_truthy
end
it "should know if it has been saved yet" do
experiment.save
expect(experiment.new_record?).to be_falsey
end
end
describe "control" do
it "should be the first alternative" do
experiment.save
expect(experiment.control.name).to eq("Basket")
end
end
end
describe "initialization" do
it "should set the algorithm when passed as an option to the initializer" do
experiment = Split::Experiment.new("basket_text", alternatives: ["Basket", "Cart"], algorithm: Split::Algorithms::Whiplash)
expect(experiment.algorithm).to eq(Split::Algorithms::Whiplash)
end
it "should be possible to make an experiment not resettable" do
experiment = Split::Experiment.new("basket_text", alternatives: ["Basket", "Cart"], resettable: false)
expect(experiment.resettable).to be_falsey
end
context "from configuration" do
let(:experiment_name) { :my_experiment }
let(:experiments) do
{
experiment_name => {
alternatives: ["Control Opt", "Alt one"]
}
}
end
before { Split.configuration.experiments = experiments }
it "assigns default values to the experiment" do
expect(Split::Experiment.new(experiment_name).resettable).to eq(true)
end
end
end
describe "persistent configuration" do
it "should persist resettable in redis" do
experiment = Split::Experiment.new("basket_text", alternatives: ["Basket", "Cart"], resettable: false)
experiment.save
e = Split::ExperimentCatalog.find("basket_text")
expect(e).to eq(experiment)
expect(e.resettable).to be_falsey
end
describe "#metadata" do
let(:experiment) { Split::Experiment.new("basket_text", alternatives: ["Basket", "Cart"], algorithm: Split::Algorithms::Whiplash, metadata: meta) }
let(:meta) { { a: "b" } }
before do
experiment.save
end
it "should delete the key when metadata is removed" do
experiment.metadata = nil
experiment.save
expect(Split.redis.exists?(experiment.metadata_key)).to be_falsey
end
context "simple hash" do
let(:meta) { { "basket" => "a", "cart" => "b" } }
it "should persist metadata in redis" do
e = Split::ExperimentCatalog.find("basket_text")
expect(e).to eq(experiment)
expect(e.metadata).to eq(meta)
end
end
context "nested hash" do
let(:meta) { { "basket" => { "one" => "two" }, "cart" => "b" } }
it "should persist metadata in redis" do
e = Split::ExperimentCatalog.find("basket_text")
expect(e).to eq(experiment)
expect(e.metadata).to eq(meta)
end
end
end
it "should persist algorithm in redis" do
experiment = Split::Experiment.new("basket_text", alternatives: ["Basket", "Cart"], algorithm: Split::Algorithms::Whiplash)
experiment.save
e = Split::ExperimentCatalog.find("basket_text")
expect(e).to eq(experiment)
expect(e.algorithm).to eq(Split::Algorithms::Whiplash)
end
it "should persist a new experiment in redis, that does not exist in the configuration file" do
experiment = Split::Experiment.new("foobar", alternatives: ["tra", "la"], algorithm: Split::Algorithms::Whiplash)
experiment.save
e = Split::ExperimentCatalog.find("foobar")
expect(e).to eq(experiment)
expect(e.alternatives.collect { |a| a.name }).to eq(["tra", "la"])
end
end
describe "deleting" do
it "should delete itself" do
experiment = Split::Experiment.new("basket_text", alternatives: [ "Basket", "Cart"])
experiment.save
experiment.delete
expect(Split.redis.exists?("link_color")).to be false
expect(Split::ExperimentCatalog.find("link_color")).to be_nil
end
it "should increment the version" do
expect(experiment.version).to eq(0)
experiment.delete
expect(experiment.version).to eq(1)
end
it "should call the on_experiment_delete hook" do
expect(Split.configuration.on_experiment_delete).to receive(:call)
experiment.delete
end
it "should call the on_before_experiment_delete hook" do
expect(Split.configuration.on_before_experiment_delete).to receive(:call)
experiment.delete
end
it "should reset the start time if the experiment should be manually started" do
Split.configuration.start_manually = true
experiment.start
experiment.delete
expect(experiment.start_time).to be_nil
end
it "should default cohorting back to false" do
experiment.disable_cohorting
expect(experiment.cohorting_disabled?).to eq(true)
experiment.delete
expect(experiment.cohorting_disabled?).to eq(false)
end
end
describe "winner" do
it "should have no winner initially" do
expect(experiment.winner).to be_nil
end
end
describe "winner=" do
it "should allow you to specify a winner" do
experiment.save
experiment.winner = "red"
expect(experiment.winner.name).to eq("red")
end
it "should call the on_experiment_winner_choose hook" do
expect(Split.configuration.on_experiment_winner_choose).to receive(:call)
experiment.winner = "green"
end
context "when has_winner state is memoized" do
before { expect(experiment).to_not have_winner }
it "should keep has_winner state consistent" do
experiment.winner = "red"
expect(experiment).to have_winner
end
end
end
describe "reset_winner" do
before { experiment.winner = "green" }
it "should reset the winner" do
experiment.reset_winner
expect(experiment.winner).to be_nil
end
context "when has_winner state is memoized" do
before { expect(experiment).to have_winner }
it "should keep has_winner state consistent" do
experiment.reset_winner
expect(experiment).to_not have_winner
end
end
end
describe "has_winner?" do
context "with winner" do
before { experiment.winner = "red" }
it "returns true" do
expect(experiment).to have_winner
end
end
context "without winner" do
it "returns false" do
expect(experiment).to_not have_winner
end
end
it "memoizes has_winner state" do
expect(experiment).to receive(:winner).once
expect(experiment).to_not have_winner
expect(experiment).to_not have_winner
end
end
describe "reset" do
let(:reset_manually) { false }
before do
allow(Split.configuration).to receive(:reset_manually).and_return(reset_manually)
experiment.save
green.increment_participation
green.increment_participation
end
it "should reset all alternatives" do
experiment.winner = "green"
expect(experiment.next_alternative.name).to eq("green")
green.increment_participation
experiment.reset
expect(green.participant_count).to eq(0)
expect(green.completed_count).to eq(0)
end
it "should reset the winner" do
experiment.winner = "green"
expect(experiment.next_alternative.name).to eq("green")
green.increment_participation
experiment.reset
expect(experiment.winner).to be_nil
end
it "should increment the version" do
expect(experiment.version).to eq(0)
experiment.reset
expect(experiment.version).to eq(1)
end
it "should call the on_experiment_reset hook" do
expect(Split.configuration.on_experiment_reset).to receive(:call)
experiment.reset
end
it "should call the on_before_experiment_reset hook" do
expect(Split.configuration.on_before_experiment_reset).to receive(:call)
experiment.reset
end
end
describe "algorithm" do
let(:experiment) { Split::ExperimentCatalog.find_or_create("link_color", "blue", "red", "green") }
it "should use the default algorithm if none is specified" do
expect(experiment.algorithm).to eq(Split.configuration.algorithm)
end
it "should use the user specified algorithm for this experiment if specified" do
experiment.algorithm = Split::Algorithms::Whiplash
expect(experiment.algorithm).to eq(Split::Algorithms::Whiplash)
end
end
end
end
end
describe "#cohorting_disabled?" do
it "returns false when nothing has been configured" do
expect(experiment.cohorting_disabled?).to eq false
end
it "returns true when enable_cohorting is performed" do
experiment.enable_cohorting
expect(experiment.cohorting_disabled?).to eq false
end
it "returns false when nothing has been configured" do
experiment.disable_cohorting
expect(experiment.cohorting_disabled?).to eq true
end
end
describe "changing an existing experiment" do
def same_but_different_alternative
Split::ExperimentCatalog.find_or_create("link_color", "blue", "yellow", "orange")
end
it "should reset an experiment if it is loaded with different alternatives" do
experiment.save
blue.participant_count = 5
same_experiment = same_but_different_alternative
expect(same_experiment.alternatives.map(&:name)).to eq(["blue", "yellow", "orange"])
expect(blue.participant_count).to eq(0)
end
it "should only reset once" do
experiment.save
expect(experiment.version).to eq(0)
same_experiment = same_but_different_alternative
expect(same_experiment.version).to eq(1)
same_experiment_again = same_but_different_alternative
expect(same_experiment_again.version).to eq(1)
end
context "when metadata is changed" do
it "should increase version" do
experiment.save
experiment.metadata = { "foo" => "bar" }
expect { experiment.save }.to change { experiment.version }.by(1)
end
it "does not increase version" do
experiment.metadata = nil
experiment.save
expect { experiment.save }.to change { experiment.version }.by(0)
end
end
context "when experiment configuration is changed" do
let(:reset_manually) { false }
before do
experiment.save
allow(Split.configuration).to receive(:reset_manually).and_return(reset_manually)
green.increment_participation
green.increment_participation
experiment.set_alternatives_and_options(alternatives: %w(blue red green zip),
goals: %w(purchase))
experiment.save
end
it "resets all alternatives" do
expect(green.participant_count).to eq(0)
expect(green.completed_count).to eq(0)
end
context "when reset_manually is set" do
let(:reset_manually) { true }
it "does not reset alternatives" do
expect(green.participant_count).to eq(2)
expect(green.completed_count).to eq(0)
end
end
end
end
describe "alternatives passed as non-strings" do
it "should throw an exception if an alternative is passed that is not a string" do
expect { Split::ExperimentCatalog.find_or_create("link_color", :blue, :red) }.to raise_error(ArgumentError)
expect { Split::ExperimentCatalog.find_or_create("link_enabled", true, false) }.to raise_error(ArgumentError)
end
end
describe "specifying weights" do
let(:experiment_with_weight) {
Split::ExperimentCatalog.find_or_create("link_color", { "blue" => 1 }, { "red" => 2 })
}
it "should work for a new experiment" do
expect(experiment_with_weight.alternatives.map(&:weight)).to eq([1, 2])
end
it "should work for an existing experiment" do
experiment.save
expect(experiment_with_weight.alternatives.map(&:weight)).to eq([1, 2])
end
end
describe "specifying goals" do
let(:experiment) {
new_experiment(["purchase"])
}
context "saving experiment" do
let(:same_but_different_goals) { Split::ExperimentCatalog.find_or_create({ "link_color" => ["purchase", "refund"] }, "blue", "red", "green") }
before { experiment.save }
it "can find existing experiment" do
expect(Split::ExperimentCatalog.find("link_color").name).to eq("link_color")
end
it "should reset an experiment if it is loaded with different goals" do
same_but_different_goals
expect(Split::ExperimentCatalog.find("link_color").goals).to eq(["purchase", "refund"])
end
end
it "should have goals" do
expect(experiment.goals).to eq(["purchase"])
end
context "find or create experiment" do
it "should have correct goals" do
experiment = Split::ExperimentCatalog.find_or_create({ "link_color3" => ["purchase", "refund"] }, "blue", "red", "green")
expect(experiment.goals).to eq(["purchase", "refund"])
experiment = Split::ExperimentCatalog.find_or_create("link_color3", "blue", "red", "green")
expect(experiment.goals).to eq([])
end
end
end
describe "beta probability calculation" do
it "should return a hash with the probability of each alternative being the best" do
experiment = Split::ExperimentCatalog.find_or_create("mathematicians", "bernoulli", "poisson", "lagrange")
experiment.calc_winning_alternatives
expect(experiment.alternative_probabilities).not_to be_nil
end
it "should return between 46% and 54% probability for an experiment with 2 alternatives and no data" do
experiment = Split::ExperimentCatalog.find_or_create("scientists", "einstein", "bohr")
experiment.calc_winning_alternatives
expect(experiment.alternatives[0].p_winner).to be_within(0.04).of(0.50)
end
it "should calculate the probability of being the winning alternative separately for each goal", skip: true do
experiment = Split::ExperimentCatalog.find_or_create({ "link_color3" => ["purchase", "refund"] }, "blue", "red", "green")
goal1 = experiment.goals[0]
goal2 = experiment.goals[1]
experiment.alternatives.each do |alternative|
alternative.participant_count = 50
alternative.set_completed_count(10, goal1)
alternative.set_completed_count(15+rand(30), goal2)
end
experiment.calc_winning_alternatives
alt = experiment.alternatives[0]
p_goal1 = alt.p_winner(goal1)
p_goal2 = alt.p_winner(goal2)
expect(p_goal1).not_to be_within(0.04).of(p_goal2)
end
it "should return nil and not re-calculate probabilities if they have already been calculated today" do
experiment = Split::ExperimentCatalog.find_or_create({ "link_color3" => ["purchase", "refund"] }, "blue", "red", "green")
expect(experiment.calc_winning_alternatives).not_to be nil
expect(experiment.calc_winning_alternatives).to be nil
end
end
end
<MSG> Adds functionality which uses the beta distribution to calculate the probability an alternative is the winner. Necessary for comparing more than 2 alternatives.
<DFF> @@ -377,4 +377,34 @@ describe Split::Experiment do
end
end
+ describe "beta probability calculation" do
+ it "should return a hash with the probability of each alternative being the best" do
+ experiment = Split::Experiment.find_or_create('mathematicians', 'bernoulli', 'poisson', 'lagrange')
+ experiment.calc_winning_alternatives
+ experiment.alternative_probabilities.should_not be_nil
+ end
+
+ it "should return between 46% and 54% probability for an experiment with 2 alternatives and no data" do
+ experiment = Split::Experiment.find_or_create('scientists', 'einstein', 'bohr')
+ experiment.calc_winning_alternatives
+ experiment.alternatives[0].p_winner.should be_within(0.04).of(0.50)
+ end
+
+ it "should calculate the probability of being the winning alternative separately for each goal" do
+ experiment = Split::Experiment.find_or_create({'link_color3' => ["purchase", "refund"]}, 'blue', 'red', 'green')
+ goal1 = experiment.goals[0]
+ goal2 = experiment.goals[1]
+ experiment.alternatives.each do |alternative|
+ alternative.participant_count = 50
+ alternative.set_completed_count(10, goal1)
+ alternative.set_completed_count(10+rand(30), goal2)
+ end
+ experiment.calc_winning_alternatives
+ alt = experiment.alternatives[0]
+ p_goal1 = alt.p_winner(goal1)
+ p_goal2 = alt.p_winner(goal2)
+ p_goal1.should_not be_within(0.04).of(p_goal2)
+ end
+ end
+
end
| 30 | Adds functionality which uses the beta distribution to calculate the probability an alternative is the winner. Necessary for comparing more than 2 alternatives. | 0 | .rb | rb | mit | splitrb/split |
10071886 | <NME> tests.py
<BEF> import unittest
import StringIO
from djangopypi.views import parse_weird_post_data
def create_post_data(action):
data = {
from django.contrib.auth.models import User
from django.http import HttpRequest
def create_post_data(action):
data = {
":action": action,
"metadata_version": "1.0",
"name": "foo",
"version": "0.1.0-pre2",
"summary": "The quick brown fox jumps over the lazy dog.",
"home_page": "http://example.com",
"author": "Foo Bar Baz",
"author_email": "[email protected]",
"license": "Apache",
"keywords": "foo bar baz",
"platform": "UNKNOWN",
"classifiers": [
"Development Status :: 3 - Alpha",
"Environment :: Web Environment",
"Framework :: Django",
"Operating System :: OS Independent",
"Intended Audience :: Developers",
"Intended Audience :: System Administrators",
"License :: OSI Approved :: BSD License",
"Topic :: System :: Software Distribution",
"Programming Language :: Python",
],
"download_url": "",
"provides": "",
"requires": "",
"obsoletes": "",
"description": """
=========
FOOBARBAZ
=========
Introduction
------------
``foo`` :class:`bar`
*baz*
[foaoa]
""",
}
return data
def create_request(data):
boundary = '--------------GHSKFJDLGDS7543FJKLFHRE75642756743254'
sep_boundary = '\n--' + boundary
end_boundary = sep_boundary + '--'
body = StringIO.StringIO()
for key, value in data.items():
# handle multiple entries for the same name
if type(value) not in (type([]), type( () )):
value = [value]
for value in value:
value = unicode(value).encode("utf-8")
body.write(sep_boundary)
body.write('\nContent-Disposition: form-data; name="%s"'%key)
body.write("\n\n")
body.write(value)
return body.getvalue()
class TestParseWeirdPostData(unittest.TestCase):
def test_weird_post_data(self):
data = create_post_data("submit")
raw_post_data = create_request(data)
post, files = parse_weird_post_data(raw_post_data)
self.assertTrue(post)
for key in post.keys():
post, files = parse_distutils_request(MockRequest(raw_post_data))
self.assertTrue(post)
for key in post.keys():
if isinstance(data[key], list):
self.assertEquals(data[key], post.getlist(key))
elif data[key] == "UNKNOWN":
self.assertTrue(post[key] is None)
else:
self.assertEquals(post[key], data[key])
client = Client()
class TestSearch(unittest.TestCase):
def setUp(self):
dummy_user = User.objects.create(username='krill', password='12345',
email='[email protected]')
Project.objects.create(name='foo', license='Gnu',
summary="The quick brown fox jumps over the lazy dog.",
owner=dummy_user)
def test_search_for_package(self):
response = client.post(reverse('djangopypi-search'), {'search_term': 'foo'})
self.assertTrue("The quick brown fox jumps over the lazy dog." in response.content)
class TestSimpleView(unittest.TestCase):
def create_distutils_httprequest(self, user_data={}):
self.post_data = create_post_data(action='user')
self.post_data.update(user_data)
self.raw_post_data = create_request(self.post_data)
request = HttpRequest()
request.POST = self.post_data
request.method = "POST"
request.raw_post_data = self.raw_post_data
return request
def test_user_registration(self):
request = self.create_distutils_httprequest({'name': 'peter_parker', 'email':'[email protected]',
'password':'spiderman'})
response = simple(request)
self.assertEquals(200, response.status_code)
def test_user_registration_with_wrong_data(self):
request = self.create_distutils_httprequest({'name': 'peter_parker', 'email':'[email protected]',
'password':'',})
response = simple(request)
self.assertEquals(400, response.status_code)
<MSG> Merge branch 'brosner/master'
Conflicts:
djangopypi/views.py
<DFF> @@ -1,6 +1,6 @@
import unittest
import StringIO
-from djangopypi.views import parse_weird_post_data
+from djangopypi.views import parse_distutils_request
def create_post_data(action):
data = {
@@ -67,12 +67,20 @@ def create_request(data):
return body.getvalue()
+class MockRequest(object):
+
+ def __init__(self, raw_post_data):
+ self.raw_post_data = raw_post_data
+ self.META = {}
+
+
class TestParseWeirdPostData(unittest.TestCase):
def test_weird_post_data(self):
data = create_post_data("submit")
raw_post_data = create_request(data)
- post, files = parse_weird_post_data(raw_post_data)
+ post, files = parse_distutils_request(MockRequest(raw_post_data))
+ print("post: %s files: %s" % (post, files))
self.assertTrue(post)
for key in post.keys():
| 10 | Merge branch 'brosner/master' | 2 | .py | py | bsd-3-clause | ask/chishop |
10071887 | <NME> urls.py
<BEF> # -*- coding: utf-8 -*-
from django.conf.urls.defaults import patterns, url, include
urlpatterns = patterns("djangopypi.views",
# Simple PyPI
url(r'^simple/$', "simple",
name="djangopypi-simple"),
url(r'^simple/(?P<dist_name>[\w\d_\.\-]+)/(?P<version>[\w\.\d\-_]+)/$',
"show_version",
name="djangopypi-show_version"),
url(r'^simple/(?P<dist_name>[\w\d_\.\-]+)/$', "show_links",
name="djangopypi-show_links"),
url(r'^$', "simple", {'template_name': 'djangopypi/pypi.html'},
name="djangopypi-pypi"),
url(r'^(?P<dist_name>[\w\d_\.\-]+)/$', "show_links",
{'template_name': 'djangopypi/pypi_show_links.html'},
name="djangopypi-pypi_show_links"),
)
<MSG> Started search engine implementation - no totally integrated yet :(
<DFF> @@ -19,5 +19,6 @@ urlpatterns = patterns("djangopypi.views",
url(r'^(?P<dist_name>[\w\d_\.\-]+)/$', "show_links",
{'template_name': 'djangopypi/pypi_show_links.html'},
name="djangopypi-pypi_show_links"),
-)
-
+
+ url(r'^search','search',name='djangopypi-search')
+)
\ No newline at end of file
| 3 | Started search engine implementation - no totally integrated yet :( | 2 | .py | py | bsd-3-clause | ask/chishop |
10071888 | <NME> engine.rb
<BEF> # frozen_string_literal: true
class Engine < ::Rails::Engine
initializer "split" do |app|
if Split.configuration.include_rails_helper
ActionController::Base.send :include, Split::Helper
ActionController::Base.helper Split::Helper
ActionController::Base.send :include, Split::CombinedExperimentsHelper
ActionController::Base.helper Split::CombinedExperimentsHelper
end
end
end
end
end
<MSG> Lazily include split helpers in ActionController::Base
<DFF> @@ -3,10 +3,12 @@ module Split
class Engine < ::Rails::Engine
initializer "split" do |app|
if Split.configuration.include_rails_helper
- ActionController::Base.send :include, Split::Helper
- ActionController::Base.helper Split::Helper
- ActionController::Base.send :include, Split::CombinedExperimentsHelper
- ActionController::Base.helper Split::CombinedExperimentsHelper
+ ActiveSupport.on_load(:action_controller) do
+ include Split::Helper
+ helper Split::Helper
+ include Split::CombinedExperimentsHelper
+ helper Split::CombinedExperimentsHelper
+ end
end
end
end
| 6 | Lazily include split helpers in ActionController::Base | 4 | .rb | rb | mit | splitrb/split |
10071889 | <NME> engine.rb
<BEF> # frozen_string_literal: true
class Engine < ::Rails::Engine
initializer "split" do |app|
if Split.configuration.include_rails_helper
ActionController::Base.send :include, Split::Helper
ActionController::Base.helper Split::Helper
ActionController::Base.send :include, Split::CombinedExperimentsHelper
ActionController::Base.helper Split::CombinedExperimentsHelper
end
end
end
end
end
<MSG> Lazily include split helpers in ActionController::Base
<DFF> @@ -3,10 +3,12 @@ module Split
class Engine < ::Rails::Engine
initializer "split" do |app|
if Split.configuration.include_rails_helper
- ActionController::Base.send :include, Split::Helper
- ActionController::Base.helper Split::Helper
- ActionController::Base.send :include, Split::CombinedExperimentsHelper
- ActionController::Base.helper Split::CombinedExperimentsHelper
+ ActiveSupport.on_load(:action_controller) do
+ include Split::Helper
+ helper Split::Helper
+ include Split::CombinedExperimentsHelper
+ helper Split::CombinedExperimentsHelper
+ end
end
end
end
| 6 | Lazily include split helpers in ActionController::Base | 4 | .rb | rb | mit | splitrb/split |
10071890 | <NME> engine.rb
<BEF> # frozen_string_literal: true
class Engine < ::Rails::Engine
initializer "split" do |app|
if Split.configuration.include_rails_helper
ActionController::Base.send :include, Split::Helper
ActionController::Base.helper Split::Helper
ActionController::Base.send :include, Split::CombinedExperimentsHelper
ActionController::Base.helper Split::CombinedExperimentsHelper
end
end
end
end
end
<MSG> Lazily include split helpers in ActionController::Base
<DFF> @@ -3,10 +3,12 @@ module Split
class Engine < ::Rails::Engine
initializer "split" do |app|
if Split.configuration.include_rails_helper
- ActionController::Base.send :include, Split::Helper
- ActionController::Base.helper Split::Helper
- ActionController::Base.send :include, Split::CombinedExperimentsHelper
- ActionController::Base.helper Split::CombinedExperimentsHelper
+ ActiveSupport.on_load(:action_controller) do
+ include Split::Helper
+ helper Split::Helper
+ include Split::CombinedExperimentsHelper
+ helper Split::CombinedExperimentsHelper
+ end
end
end
end
| 6 | Lazily include split helpers in ActionController::Base | 4 | .rb | rb | mit | splitrb/split |
10071891 | <NME> trial_spec.rb
<BEF> # frozen_string_literal: true
require "spec_helper"
require "split/trial"
describe Split::Trial do
let(:user) { mock_user }
let(:alternatives) { ["basket", "cart"] }
let(:experiment) do
Split::Experiment.new("basket_text", alternatives: alternatives).save
end
it "should be initializeable" do
experiment = double("experiment")
alternative = double("alternative", kind_of?: Split::Alternative)
trial = Split::Trial.new(experiment: experiment, alternative: alternative)
expect(trial.experiment).to eq(experiment)
expect(trial.alternative).to eq(alternative)
it "should call select_alternative if nil" do
trial = Split::Trial.new(experiment: experiment = mock('experiment'))
trial.should_receive(:choose).and_return(alternative = mock('alternative'))
alternative.should_receive(:increment_participation)
trial.choose!
trial.alternative.should == alternative
end
it "should load the alternative when the alternative name is set" do
experiment = Split::Experiment.new("basket_text", alternatives: ["basket", "cart"])
experiment.save
trial = Split::Trial.new(experiment: experiment, alternative: "basket")
expect(trial.alternative.name).to eq("basket")
end
end
describe "metadata" do
let(:metadata) { Hash[alternatives.map { |k| [k, "Metadata for #{k}"] }] }
let(:experiment) do
Split::Experiment.new("basket_text", alternatives: alternatives, metadata: metadata).save
end
it "has metadata on each trial" do
trial = Split::Trial.new(experiment: experiment, user: user, metadata: metadata["cart"],
override: "cart")
expect(trial.metadata).to eq(metadata["cart"])
end
it "has metadata on each trial from the experiment" do
trial = Split::Trial.new(experiment: experiment, user: user)
trial.choose!
expect(trial.metadata).to eq(metadata[trial.alternative.name])
expect(trial.metadata).to match(/#{trial.alternative.name}/)
end
end
describe "#choose!" do
let(:context) { double(on_trial_callback: "test callback") }
let(:trial) do
Split::Trial.new(user: user, experiment: experiment)
end
shared_examples_for "a trial with callbacks" do
it "does not run if on_trial callback is not respondable" do
Split.configuration.on_trial = :foo
allow(context).to receive(:respond_to?).with(:foo, true).and_return false
expect(context).to_not receive(:foo)
trial.choose! context
end
it "runs on_trial callback" do
Split.configuration.on_trial = :on_trial_callback
expect(context).to receive(:on_trial_callback)
trial.choose! context
end
it "does not run nil on_trial callback" do
Split.configuration.on_trial = nil
expect(context).not_to receive(:on_trial_callback)
trial.choose! context
end
end
def expect_alternative(trial, alternative_name)
3.times do
trial.choose! context
expect(alternative_name).to include(trial.alternative.name)
end
end
context "when override is present" do
let(:override) { "cart" }
let(:trial) do
Split::Trial.new(user: user, experiment: experiment, override: override)
end
it_behaves_like "a trial with callbacks"
it "picks the override" do
expect(experiment).to_not receive(:next_alternative)
expect_alternative(trial, override)
end
context "when alternative doesn't exist" do
let(:override) { nil }
it "falls back on next_alternative" do
expect(experiment).to receive(:next_alternative).and_call_original
expect_alternative(trial, alternatives)
end
end
end
context "when disabled option is true" do
let(:trial) do
Split::Trial.new(user: user, experiment: experiment, disabled: true)
end
it "picks the control", :aggregate_failures do
Split.configuration.on_trial = :on_trial_callback
expect(experiment).to_not receive(:next_alternative)
expect(context).not_to receive(:on_trial_callback)
expect_alternative(trial, "basket")
Split.configuration.on_trial = nil
end
end
context "when Split is globally disabled" do
it "picks the control and does not run on_trial callbacks", :aggregate_failures do
Split.configuration.enabled = false
Split.configuration.on_trial = :on_trial_callback
expect(experiment).to_not receive(:next_alternative)
expect(context).not_to receive(:on_trial_callback)
expect_alternative(trial, "basket")
Split.configuration.enabled = true
Split.configuration.on_trial = nil
end
end
context "when experiment has winner" do
let(:trial) do
Split::Trial.new(user: user, experiment: experiment)
end
it_behaves_like "a trial with callbacks"
it "picks the winner" do
experiment.winner = "cart"
expect(experiment).to_not receive(:next_alternative)
expect_alternative(trial, "cart")
end
end
context "when exclude is true" do
let(:trial) do
Split::Trial.new(user: user, experiment: experiment, exclude: true)
end
it_behaves_like "a trial with callbacks"
it "picks the control" do
expect(experiment).to_not receive(:next_alternative)
expect_alternative(trial, "basket")
end
end
context "when user is already participating" do
it_behaves_like "a trial with callbacks"
it "picks the same alternative" do
user[experiment.key] = "basket"
expect(experiment).to_not receive(:next_alternative)
expect_alternative(trial, "basket")
end
context "when alternative is not found" do
it "falls back on next_alternative" do
user[experiment.key] = "notfound"
expect(experiment).to receive(:next_alternative).and_call_original
expect_alternative(trial, alternatives)
end
end
end
context "when user is a new participant" do
it "picks a new alternative and runs on_trial_choose callback", :aggregate_failures do
Split.configuration.on_trial_choose = :on_trial_choose_callback
expect(experiment).to receive(:next_alternative).and_call_original
expect(context).to receive(:on_trial_choose_callback)
trial.choose! context
expect(trial.alternative.name).to_not be_empty
Split.configuration.on_trial_choose = nil
end
it "assigns user to an alternative" do
trial.choose! context
expect(alternatives).to include(user[experiment.name])
end
context "when cohorting is disabled" do
before(:each) { allow(experiment).to receive(:cohorting_disabled?).and_return(true) }
it "picks the control and does not run on_trial callbacks" do
Split.configuration.on_trial = :on_trial_callback
expect(experiment).to_not receive(:next_alternative)
expect(context).not_to receive(:on_trial_callback)
expect_alternative(trial, "basket")
Split.configuration.enabled = true
Split.configuration.on_trial = nil
end
it "user is not assigned an alternative" do
trial.choose! context
expect(user[experiment]).to eq(nil)
end
end
end
end
describe "#complete!" do
context "when there are no goals" do
let(:trial) { Split::Trial.new(user: user, experiment: experiment) }
it "should complete the trial" do
trial.choose!
old_completed_count = trial.alternative.completed_count
trial.complete!
expect(trial.alternative.completed_count).to eq(old_completed_count + 1)
end
end
context "when there are many goals" do
let(:goals) { [ "goal1", "goal2" ] }
let(:trial) { Split::Trial.new(user: user, experiment: experiment, goals: goals) }
it "increments the completed count corresponding to the goals" do
trial.choose!
old_completed_counts = goals.map { |goal| [goal, trial.alternative.completed_count(goal)] }.to_h
trial.complete!
goals.each { | goal | expect(trial.alternative.completed_count(goal)).to eq(old_completed_counts[goal] + 1) }
end
end
context "when there is 1 goal of type string" do
let(:goal) { "goal" }
let(:trial) { Split::Trial.new(user: user, experiment: experiment, goals: goal) }
it "increments the completed count corresponding to the goal" do
trial.choose!
old_completed_count = trial.alternative.completed_count(goal)
trial.complete!
expect(trial.alternative.completed_count(goal)).to eq(old_completed_count + 1)
end
end
end
describe "alternative recording" do
before(:each) { Split.configuration.store_override = false }
context "when override is present" do
it "stores when store_override is true" do
trial = Split::Trial.new(user: user, experiment: experiment, override: "basket")
Split.configuration.store_override = true
expect(user).to receive("[]=")
trial.choose!
expect(trial.alternative.participant_count).to eq(1)
end
it "does not store when store_override is false" do
trial = Split::Trial.new(user: user, experiment: experiment, override: "basket")
expect(user).to_not receive("[]=")
trial.choose!
end
end
context "when disabled is present" do
it "stores when store_override is true" do
trial = Split::Trial.new(user: user, experiment: experiment, disabled: true)
Split.configuration.store_override = true
expect(user).to receive("[]=")
trial.choose!
end
it "does not store when store_override is false" do
trial = Split::Trial.new(user: user, experiment: experiment, disabled: true)
expect(user).to_not receive("[]=")
trial.choose!
end
end
context "when exclude is present" do
it "does not store" do
trial = Split::Trial.new(user: user, experiment: experiment, exclude: true)
expect(user).to_not receive("[]=")
trial.choose!
end
end
context "when experiment has winner" do
let(:trial) do
experiment.winner = "cart"
Split::Trial.new(user: user, experiment: experiment)
end
it "does not store" do
expect(user).to_not receive("[]=")
trial.choose!
end
end
end
end
<MSG> merge from master.
<DFF> @@ -19,8 +19,9 @@ describe Split::Trial do
it "should call select_alternative if nil" do
trial = Split::Trial.new(experiment: experiment = mock('experiment'))
- trial.should_receive(:choose).and_return(alternative = mock('alternative'))
+ experiment.should_receive(:next_alternative).and_return(alternative = mock('alternative'))
alternative.should_receive(:increment_participation)
+ experiment.should_receive(:winner).and_return nil
trial.choose!
trial.alternative.should == alternative
| 2 | merge from master. | 1 | .rb | rb | mit | splitrb/split |
10071892 | <NME> trial_spec.rb
<BEF> # frozen_string_literal: true
require "spec_helper"
require "split/trial"
describe Split::Trial do
let(:user) { mock_user }
let(:alternatives) { ["basket", "cart"] }
let(:experiment) do
Split::Experiment.new("basket_text", alternatives: alternatives).save
end
it "should be initializeable" do
experiment = double("experiment")
alternative = double("alternative", kind_of?: Split::Alternative)
trial = Split::Trial.new(experiment: experiment, alternative: alternative)
expect(trial.experiment).to eq(experiment)
expect(trial.alternative).to eq(alternative)
it "should call select_alternative if nil" do
trial = Split::Trial.new(experiment: experiment = mock('experiment'))
trial.should_receive(:choose).and_return(alternative = mock('alternative'))
alternative.should_receive(:increment_participation)
trial.choose!
trial.alternative.should == alternative
end
it "should load the alternative when the alternative name is set" do
experiment = Split::Experiment.new("basket_text", alternatives: ["basket", "cart"])
experiment.save
trial = Split::Trial.new(experiment: experiment, alternative: "basket")
expect(trial.alternative.name).to eq("basket")
end
end
describe "metadata" do
let(:metadata) { Hash[alternatives.map { |k| [k, "Metadata for #{k}"] }] }
let(:experiment) do
Split::Experiment.new("basket_text", alternatives: alternatives, metadata: metadata).save
end
it "has metadata on each trial" do
trial = Split::Trial.new(experiment: experiment, user: user, metadata: metadata["cart"],
override: "cart")
expect(trial.metadata).to eq(metadata["cart"])
end
it "has metadata on each trial from the experiment" do
trial = Split::Trial.new(experiment: experiment, user: user)
trial.choose!
expect(trial.metadata).to eq(metadata[trial.alternative.name])
expect(trial.metadata).to match(/#{trial.alternative.name}/)
end
end
describe "#choose!" do
let(:context) { double(on_trial_callback: "test callback") }
let(:trial) do
Split::Trial.new(user: user, experiment: experiment)
end
shared_examples_for "a trial with callbacks" do
it "does not run if on_trial callback is not respondable" do
Split.configuration.on_trial = :foo
allow(context).to receive(:respond_to?).with(:foo, true).and_return false
expect(context).to_not receive(:foo)
trial.choose! context
end
it "runs on_trial callback" do
Split.configuration.on_trial = :on_trial_callback
expect(context).to receive(:on_trial_callback)
trial.choose! context
end
it "does not run nil on_trial callback" do
Split.configuration.on_trial = nil
expect(context).not_to receive(:on_trial_callback)
trial.choose! context
end
end
def expect_alternative(trial, alternative_name)
3.times do
trial.choose! context
expect(alternative_name).to include(trial.alternative.name)
end
end
context "when override is present" do
let(:override) { "cart" }
let(:trial) do
Split::Trial.new(user: user, experiment: experiment, override: override)
end
it_behaves_like "a trial with callbacks"
it "picks the override" do
expect(experiment).to_not receive(:next_alternative)
expect_alternative(trial, override)
end
context "when alternative doesn't exist" do
let(:override) { nil }
it "falls back on next_alternative" do
expect(experiment).to receive(:next_alternative).and_call_original
expect_alternative(trial, alternatives)
end
end
end
context "when disabled option is true" do
let(:trial) do
Split::Trial.new(user: user, experiment: experiment, disabled: true)
end
it "picks the control", :aggregate_failures do
Split.configuration.on_trial = :on_trial_callback
expect(experiment).to_not receive(:next_alternative)
expect(context).not_to receive(:on_trial_callback)
expect_alternative(trial, "basket")
Split.configuration.on_trial = nil
end
end
context "when Split is globally disabled" do
it "picks the control and does not run on_trial callbacks", :aggregate_failures do
Split.configuration.enabled = false
Split.configuration.on_trial = :on_trial_callback
expect(experiment).to_not receive(:next_alternative)
expect(context).not_to receive(:on_trial_callback)
expect_alternative(trial, "basket")
Split.configuration.enabled = true
Split.configuration.on_trial = nil
end
end
context "when experiment has winner" do
let(:trial) do
Split::Trial.new(user: user, experiment: experiment)
end
it_behaves_like "a trial with callbacks"
it "picks the winner" do
experiment.winner = "cart"
expect(experiment).to_not receive(:next_alternative)
expect_alternative(trial, "cart")
end
end
context "when exclude is true" do
let(:trial) do
Split::Trial.new(user: user, experiment: experiment, exclude: true)
end
it_behaves_like "a trial with callbacks"
it "picks the control" do
expect(experiment).to_not receive(:next_alternative)
expect_alternative(trial, "basket")
end
end
context "when user is already participating" do
it_behaves_like "a trial with callbacks"
it "picks the same alternative" do
user[experiment.key] = "basket"
expect(experiment).to_not receive(:next_alternative)
expect_alternative(trial, "basket")
end
context "when alternative is not found" do
it "falls back on next_alternative" do
user[experiment.key] = "notfound"
expect(experiment).to receive(:next_alternative).and_call_original
expect_alternative(trial, alternatives)
end
end
end
context "when user is a new participant" do
it "picks a new alternative and runs on_trial_choose callback", :aggregate_failures do
Split.configuration.on_trial_choose = :on_trial_choose_callback
expect(experiment).to receive(:next_alternative).and_call_original
expect(context).to receive(:on_trial_choose_callback)
trial.choose! context
expect(trial.alternative.name).to_not be_empty
Split.configuration.on_trial_choose = nil
end
it "assigns user to an alternative" do
trial.choose! context
expect(alternatives).to include(user[experiment.name])
end
context "when cohorting is disabled" do
before(:each) { allow(experiment).to receive(:cohorting_disabled?).and_return(true) }
it "picks the control and does not run on_trial callbacks" do
Split.configuration.on_trial = :on_trial_callback
expect(experiment).to_not receive(:next_alternative)
expect(context).not_to receive(:on_trial_callback)
expect_alternative(trial, "basket")
Split.configuration.enabled = true
Split.configuration.on_trial = nil
end
it "user is not assigned an alternative" do
trial.choose! context
expect(user[experiment]).to eq(nil)
end
end
end
end
describe "#complete!" do
context "when there are no goals" do
let(:trial) { Split::Trial.new(user: user, experiment: experiment) }
it "should complete the trial" do
trial.choose!
old_completed_count = trial.alternative.completed_count
trial.complete!
expect(trial.alternative.completed_count).to eq(old_completed_count + 1)
end
end
context "when there are many goals" do
let(:goals) { [ "goal1", "goal2" ] }
let(:trial) { Split::Trial.new(user: user, experiment: experiment, goals: goals) }
it "increments the completed count corresponding to the goals" do
trial.choose!
old_completed_counts = goals.map { |goal| [goal, trial.alternative.completed_count(goal)] }.to_h
trial.complete!
goals.each { | goal | expect(trial.alternative.completed_count(goal)).to eq(old_completed_counts[goal] + 1) }
end
end
context "when there is 1 goal of type string" do
let(:goal) { "goal" }
let(:trial) { Split::Trial.new(user: user, experiment: experiment, goals: goal) }
it "increments the completed count corresponding to the goal" do
trial.choose!
old_completed_count = trial.alternative.completed_count(goal)
trial.complete!
expect(trial.alternative.completed_count(goal)).to eq(old_completed_count + 1)
end
end
end
describe "alternative recording" do
before(:each) { Split.configuration.store_override = false }
context "when override is present" do
it "stores when store_override is true" do
trial = Split::Trial.new(user: user, experiment: experiment, override: "basket")
Split.configuration.store_override = true
expect(user).to receive("[]=")
trial.choose!
expect(trial.alternative.participant_count).to eq(1)
end
it "does not store when store_override is false" do
trial = Split::Trial.new(user: user, experiment: experiment, override: "basket")
expect(user).to_not receive("[]=")
trial.choose!
end
end
context "when disabled is present" do
it "stores when store_override is true" do
trial = Split::Trial.new(user: user, experiment: experiment, disabled: true)
Split.configuration.store_override = true
expect(user).to receive("[]=")
trial.choose!
end
it "does not store when store_override is false" do
trial = Split::Trial.new(user: user, experiment: experiment, disabled: true)
expect(user).to_not receive("[]=")
trial.choose!
end
end
context "when exclude is present" do
it "does not store" do
trial = Split::Trial.new(user: user, experiment: experiment, exclude: true)
expect(user).to_not receive("[]=")
trial.choose!
end
end
context "when experiment has winner" do
let(:trial) do
experiment.winner = "cart"
Split::Trial.new(user: user, experiment: experiment)
end
it "does not store" do
expect(user).to_not receive("[]=")
trial.choose!
end
end
end
end
<MSG> merge from master.
<DFF> @@ -19,8 +19,9 @@ describe Split::Trial do
it "should call select_alternative if nil" do
trial = Split::Trial.new(experiment: experiment = mock('experiment'))
- trial.should_receive(:choose).and_return(alternative = mock('alternative'))
+ experiment.should_receive(:next_alternative).and_return(alternative = mock('alternative'))
alternative.should_receive(:increment_participation)
+ experiment.should_receive(:winner).and_return nil
trial.choose!
trial.alternative.should == alternative
| 2 | merge from master. | 1 | .rb | rb | mit | splitrb/split |
10071893 | <NME> trial_spec.rb
<BEF> # frozen_string_literal: true
require "spec_helper"
require "split/trial"
describe Split::Trial do
let(:user) { mock_user }
let(:alternatives) { ["basket", "cart"] }
let(:experiment) do
Split::Experiment.new("basket_text", alternatives: alternatives).save
end
it "should be initializeable" do
experiment = double("experiment")
alternative = double("alternative", kind_of?: Split::Alternative)
trial = Split::Trial.new(experiment: experiment, alternative: alternative)
expect(trial.experiment).to eq(experiment)
expect(trial.alternative).to eq(alternative)
it "should call select_alternative if nil" do
trial = Split::Trial.new(experiment: experiment = mock('experiment'))
trial.should_receive(:choose).and_return(alternative = mock('alternative'))
alternative.should_receive(:increment_participation)
trial.choose!
trial.alternative.should == alternative
end
it "should load the alternative when the alternative name is set" do
experiment = Split::Experiment.new("basket_text", alternatives: ["basket", "cart"])
experiment.save
trial = Split::Trial.new(experiment: experiment, alternative: "basket")
expect(trial.alternative.name).to eq("basket")
end
end
describe "metadata" do
let(:metadata) { Hash[alternatives.map { |k| [k, "Metadata for #{k}"] }] }
let(:experiment) do
Split::Experiment.new("basket_text", alternatives: alternatives, metadata: metadata).save
end
it "has metadata on each trial" do
trial = Split::Trial.new(experiment: experiment, user: user, metadata: metadata["cart"],
override: "cart")
expect(trial.metadata).to eq(metadata["cart"])
end
it "has metadata on each trial from the experiment" do
trial = Split::Trial.new(experiment: experiment, user: user)
trial.choose!
expect(trial.metadata).to eq(metadata[trial.alternative.name])
expect(trial.metadata).to match(/#{trial.alternative.name}/)
end
end
describe "#choose!" do
let(:context) { double(on_trial_callback: "test callback") }
let(:trial) do
Split::Trial.new(user: user, experiment: experiment)
end
shared_examples_for "a trial with callbacks" do
it "does not run if on_trial callback is not respondable" do
Split.configuration.on_trial = :foo
allow(context).to receive(:respond_to?).with(:foo, true).and_return false
expect(context).to_not receive(:foo)
trial.choose! context
end
it "runs on_trial callback" do
Split.configuration.on_trial = :on_trial_callback
expect(context).to receive(:on_trial_callback)
trial.choose! context
end
it "does not run nil on_trial callback" do
Split.configuration.on_trial = nil
expect(context).not_to receive(:on_trial_callback)
trial.choose! context
end
end
def expect_alternative(trial, alternative_name)
3.times do
trial.choose! context
expect(alternative_name).to include(trial.alternative.name)
end
end
context "when override is present" do
let(:override) { "cart" }
let(:trial) do
Split::Trial.new(user: user, experiment: experiment, override: override)
end
it_behaves_like "a trial with callbacks"
it "picks the override" do
expect(experiment).to_not receive(:next_alternative)
expect_alternative(trial, override)
end
context "when alternative doesn't exist" do
let(:override) { nil }
it "falls back on next_alternative" do
expect(experiment).to receive(:next_alternative).and_call_original
expect_alternative(trial, alternatives)
end
end
end
context "when disabled option is true" do
let(:trial) do
Split::Trial.new(user: user, experiment: experiment, disabled: true)
end
it "picks the control", :aggregate_failures do
Split.configuration.on_trial = :on_trial_callback
expect(experiment).to_not receive(:next_alternative)
expect(context).not_to receive(:on_trial_callback)
expect_alternative(trial, "basket")
Split.configuration.on_trial = nil
end
end
context "when Split is globally disabled" do
it "picks the control and does not run on_trial callbacks", :aggregate_failures do
Split.configuration.enabled = false
Split.configuration.on_trial = :on_trial_callback
expect(experiment).to_not receive(:next_alternative)
expect(context).not_to receive(:on_trial_callback)
expect_alternative(trial, "basket")
Split.configuration.enabled = true
Split.configuration.on_trial = nil
end
end
context "when experiment has winner" do
let(:trial) do
Split::Trial.new(user: user, experiment: experiment)
end
it_behaves_like "a trial with callbacks"
it "picks the winner" do
experiment.winner = "cart"
expect(experiment).to_not receive(:next_alternative)
expect_alternative(trial, "cart")
end
end
context "when exclude is true" do
let(:trial) do
Split::Trial.new(user: user, experiment: experiment, exclude: true)
end
it_behaves_like "a trial with callbacks"
it "picks the control" do
expect(experiment).to_not receive(:next_alternative)
expect_alternative(trial, "basket")
end
end
context "when user is already participating" do
it_behaves_like "a trial with callbacks"
it "picks the same alternative" do
user[experiment.key] = "basket"
expect(experiment).to_not receive(:next_alternative)
expect_alternative(trial, "basket")
end
context "when alternative is not found" do
it "falls back on next_alternative" do
user[experiment.key] = "notfound"
expect(experiment).to receive(:next_alternative).and_call_original
expect_alternative(trial, alternatives)
end
end
end
context "when user is a new participant" do
it "picks a new alternative and runs on_trial_choose callback", :aggregate_failures do
Split.configuration.on_trial_choose = :on_trial_choose_callback
expect(experiment).to receive(:next_alternative).and_call_original
expect(context).to receive(:on_trial_choose_callback)
trial.choose! context
expect(trial.alternative.name).to_not be_empty
Split.configuration.on_trial_choose = nil
end
it "assigns user to an alternative" do
trial.choose! context
expect(alternatives).to include(user[experiment.name])
end
context "when cohorting is disabled" do
before(:each) { allow(experiment).to receive(:cohorting_disabled?).and_return(true) }
it "picks the control and does not run on_trial callbacks" do
Split.configuration.on_trial = :on_trial_callback
expect(experiment).to_not receive(:next_alternative)
expect(context).not_to receive(:on_trial_callback)
expect_alternative(trial, "basket")
Split.configuration.enabled = true
Split.configuration.on_trial = nil
end
it "user is not assigned an alternative" do
trial.choose! context
expect(user[experiment]).to eq(nil)
end
end
end
end
describe "#complete!" do
context "when there are no goals" do
let(:trial) { Split::Trial.new(user: user, experiment: experiment) }
it "should complete the trial" do
trial.choose!
old_completed_count = trial.alternative.completed_count
trial.complete!
expect(trial.alternative.completed_count).to eq(old_completed_count + 1)
end
end
context "when there are many goals" do
let(:goals) { [ "goal1", "goal2" ] }
let(:trial) { Split::Trial.new(user: user, experiment: experiment, goals: goals) }
it "increments the completed count corresponding to the goals" do
trial.choose!
old_completed_counts = goals.map { |goal| [goal, trial.alternative.completed_count(goal)] }.to_h
trial.complete!
goals.each { | goal | expect(trial.alternative.completed_count(goal)).to eq(old_completed_counts[goal] + 1) }
end
end
context "when there is 1 goal of type string" do
let(:goal) { "goal" }
let(:trial) { Split::Trial.new(user: user, experiment: experiment, goals: goal) }
it "increments the completed count corresponding to the goal" do
trial.choose!
old_completed_count = trial.alternative.completed_count(goal)
trial.complete!
expect(trial.alternative.completed_count(goal)).to eq(old_completed_count + 1)
end
end
end
describe "alternative recording" do
before(:each) { Split.configuration.store_override = false }
context "when override is present" do
it "stores when store_override is true" do
trial = Split::Trial.new(user: user, experiment: experiment, override: "basket")
Split.configuration.store_override = true
expect(user).to receive("[]=")
trial.choose!
expect(trial.alternative.participant_count).to eq(1)
end
it "does not store when store_override is false" do
trial = Split::Trial.new(user: user, experiment: experiment, override: "basket")
expect(user).to_not receive("[]=")
trial.choose!
end
end
context "when disabled is present" do
it "stores when store_override is true" do
trial = Split::Trial.new(user: user, experiment: experiment, disabled: true)
Split.configuration.store_override = true
expect(user).to receive("[]=")
trial.choose!
end
it "does not store when store_override is false" do
trial = Split::Trial.new(user: user, experiment: experiment, disabled: true)
expect(user).to_not receive("[]=")
trial.choose!
end
end
context "when exclude is present" do
it "does not store" do
trial = Split::Trial.new(user: user, experiment: experiment, exclude: true)
expect(user).to_not receive("[]=")
trial.choose!
end
end
context "when experiment has winner" do
let(:trial) do
experiment.winner = "cart"
Split::Trial.new(user: user, experiment: experiment)
end
it "does not store" do
expect(user).to_not receive("[]=")
trial.choose!
end
end
end
end
<MSG> merge from master.
<DFF> @@ -19,8 +19,9 @@ describe Split::Trial do
it "should call select_alternative if nil" do
trial = Split::Trial.new(experiment: experiment = mock('experiment'))
- trial.should_receive(:choose).and_return(alternative = mock('alternative'))
+ experiment.should_receive(:next_alternative).and_return(alternative = mock('alternative'))
alternative.should_receive(:increment_participation)
+ experiment.should_receive(:winner).and_return nil
trial.choose!
trial.alternative.should == alternative
| 2 | merge from master. | 1 | .rb | rb | mit | splitrb/split |
10071894 | <NME> models.py
<BEF> import os
from django.conf import settings
from django.db import models
from django.utils.translation import ugettext_lazy as _
from django.contrib.auth.models import User
OS_NAMES = (
("aix", "AIX"),
("beos", "BeOS"),
("debian", "Debian Linux"),
("dos", "DOS"),
("freebsd", "FreeBSD"),
("hpux", "HP/UX"),
("mac", "Mac System x."),
("macos", "MacOS X"),
("mandrake", "Mandrake Linux"),
("netbsd", "NetBSD"),
("openbsd", "OpenBSD"),
("qnx", "QNX"),
("redhat", "RedHat Linux"),
("solaris", "SUN Solaris"),
("suse", "SuSE Linux"),
("yellowdog", "Yellow Dog Linux"),
)
ARCHITECTURES = (
("alpha", "Alpha"),
("hppa", "HPPA"),
("ix86", "Intel"),
("powerpc", "PowerPC"),
("sparc", "Sparc"),
("ultrasparc", "UltraSparc"),
)
UPLOAD_TO = getattr(settings,
"DJANGOPYPI_RELEASE_UPLOAD_TO", 'dist')
class Classifier(models.Model):
name = models.CharField(max_length=255, unique=True)
class Meta:
verbose_name = _(u"classifier")
verbose_name_plural = _(u"classifiers")
def __unicode__(self):
return self.name
class Project(models.Model):
name = models.CharField(max_length=255, unique=True)
license = models.TextField(blank=True)
metadata_version = models.CharField(max_length=64, default=1.0)
author = models.CharField(max_length=128, blank=True)
home_page = models.URLField(verify_exists=False, blank=True, null=True)
download_url = models.CharField(max_length=200, blank=True, null=True)
summary = models.TextField(blank=True)
description = models.TextField(blank=True)
author_email = models.CharField(max_length=255, blank=True)
classifiers = models.ManyToManyField(Classifier)
owner = models.ForeignKey(User, related_name="projects")
updated = models.DateTimeField(auto_now=True)
class Meta:
verbose_name = _(u"project")
verbose_name_plural = _(u"projects")
def __unicode__(self):
return self.name
@models.permalink
def get_absolute_url(self):
return ('djangopypi-show_links', (), {'dist_name': self.name})
@models.permalink
def get_pypi_absolute_url(self):
return ('djangopypi-pypi_show_links', (), {'dist_name': self.name})
def get_release(self, version):
"""Return the release object for version, or None"""
try:
return self.releases.get(version=version)
except Release.DoesNotExist:
return None
class Release(models.Model):
version = models.CharField(max_length=32)
distribution = models.FileField(upload_to=UPLOAD_TO)
md5_digest = models.CharField(max_length=255, blank=True)
platform = models.CharField(max_length=128, blank=True)
signature = models.CharField(max_length=128, blank=True)
filetype = models.CharField(max_length=255, blank=True)
pyversion = models.CharField(max_length=32, blank=True)
project = models.ForeignKey(Project, related_name="releases")
upload_time = models.DateTimeField(auto_now=True)
class Meta:
verbose_name = _(u"release")
verbose_name_plural = _(u"releases")
unique_together = ("project", "version", "platform", "distribution", "pyversion")
def __unicode__(self):
return u"%s (%s)" % (self.release_name, self.platform)
@property
def type(self):
dist_file_types = {
'sdist':'Source',
'bdist_dumb':'"dumb" binary',
'bdist_rpm':'RPM',
'bdist_wininst':'MS Windows installer',
'bdist_egg':'Python Egg',
'bdist_dmg':'OS X Disk Image'}
return dist_file_types.get(self.filetype, self.filetype)
@property
def filename(self):
upload_time = models.DateTimeField(auto_now=True)
class Meta:
unique_together = ('version', 'platform')
verbose_name = _(u"release")
verbose_name_plural = _(u"releases")
@property
def path(self):
return self.distribution.name
@models.permalink
def get_absolute_url(self):
return ('djangopypi-show_version', (), {'dist_name': self.project, 'version': self.version})
def get_dl_url(self):
return "%s#md5=%s" % (self.distribution.url, self.md5_digest)
<MSG> MySQL couln't handle the unique_together index on the Release model.
<DFF> @@ -117,7 +117,6 @@ class Release(models.Model):
upload_time = models.DateTimeField(auto_now=True)
class Meta:
- unique_together = ('version', 'platform')
verbose_name = _(u"release")
verbose_name_plural = _(u"releases")
| 0 | MySQL couln't handle the unique_together index on the Release model. | 1 | .py | py | bsd-3-clause | ask/chishop |
10071895 | <NME> helper_spec.rb
<BEF> ADDFILE
<MSG> ab_test helper method implemented
<DFF> @@ -0,0 +1,40 @@
+require 'spec_helper'
+
+describe Multivariate::Helper do
+ before(:each) do
+ REDIS.flushall
+ Multivariate::Helper.current_user = {}
+ end
+
+ describe "ab_test" do
+ it "should find or create an experiment from a name" do
+ Multivariate::Helper.ab_test('link_color', 'blue', 'red').should eql('blue')
+ end
+
+ it "should assign a random alternative to a new user" do
+ Multivariate::Helper.ab_test('link_color', 'blue', 'red')
+ Multivariate::Helper.current_user['link_color'].should_not == nil
+ end
+
+ it "should increment the participation counter after assignment to a new user" do
+ experiment = Multivariate::Experiment.find_or_create('link_color', 'blue', 'red')
+
+ previous_red_count = Multivariate::Alternative.find('red', 'link_color').participant_count
+ previous_blue_count = Multivariate::Alternative.find('blue', 'link_color').participant_count
+
+ Multivariate::Helper.ab_test('link_color', 'blue', 'red')
+
+ new_red_count = Multivariate::Alternative.find('red', 'link_color').participant_count
+ new_blue_count = Multivariate::Alternative.find('blue', 'link_color').participant_count
+
+ (new_red_count + new_blue_count).should eql(previous_red_count + previous_blue_count + 1)
+ end
+
+ it "should return the given alternative for an existing user" do
+ experiment = Multivariate::Experiment.find_or_create('link_color', 'blue', 'red')
+ alternative = Multivariate::Helper.ab_test('link_color', 'blue', 'red')
+ repeat_alternative = Multivariate::Helper.ab_test('link_color', 'blue', 'red')
+ alternative.should eql repeat_alternative
+ end
+ end
+end
\ No newline at end of file
| 40 | ab_test helper method implemented | 0 | .rb | rb | mit | splitrb/split |
10071896 | <NME> helper_spec.rb
<BEF> ADDFILE
<MSG> ab_test helper method implemented
<DFF> @@ -0,0 +1,40 @@
+require 'spec_helper'
+
+describe Multivariate::Helper do
+ before(:each) do
+ REDIS.flushall
+ Multivariate::Helper.current_user = {}
+ end
+
+ describe "ab_test" do
+ it "should find or create an experiment from a name" do
+ Multivariate::Helper.ab_test('link_color', 'blue', 'red').should eql('blue')
+ end
+
+ it "should assign a random alternative to a new user" do
+ Multivariate::Helper.ab_test('link_color', 'blue', 'red')
+ Multivariate::Helper.current_user['link_color'].should_not == nil
+ end
+
+ it "should increment the participation counter after assignment to a new user" do
+ experiment = Multivariate::Experiment.find_or_create('link_color', 'blue', 'red')
+
+ previous_red_count = Multivariate::Alternative.find('red', 'link_color').participant_count
+ previous_blue_count = Multivariate::Alternative.find('blue', 'link_color').participant_count
+
+ Multivariate::Helper.ab_test('link_color', 'blue', 'red')
+
+ new_red_count = Multivariate::Alternative.find('red', 'link_color').participant_count
+ new_blue_count = Multivariate::Alternative.find('blue', 'link_color').participant_count
+
+ (new_red_count + new_blue_count).should eql(previous_red_count + previous_blue_count + 1)
+ end
+
+ it "should return the given alternative for an existing user" do
+ experiment = Multivariate::Experiment.find_or_create('link_color', 'blue', 'red')
+ alternative = Multivariate::Helper.ab_test('link_color', 'blue', 'red')
+ repeat_alternative = Multivariate::Helper.ab_test('link_color', 'blue', 'red')
+ alternative.should eql repeat_alternative
+ end
+ end
+end
\ No newline at end of file
| 40 | ab_test helper method implemented | 0 | .rb | rb | mit | splitrb/split |
10071897 | <NME> helper_spec.rb
<BEF> ADDFILE
<MSG> ab_test helper method implemented
<DFF> @@ -0,0 +1,40 @@
+require 'spec_helper'
+
+describe Multivariate::Helper do
+ before(:each) do
+ REDIS.flushall
+ Multivariate::Helper.current_user = {}
+ end
+
+ describe "ab_test" do
+ it "should find or create an experiment from a name" do
+ Multivariate::Helper.ab_test('link_color', 'blue', 'red').should eql('blue')
+ end
+
+ it "should assign a random alternative to a new user" do
+ Multivariate::Helper.ab_test('link_color', 'blue', 'red')
+ Multivariate::Helper.current_user['link_color'].should_not == nil
+ end
+
+ it "should increment the participation counter after assignment to a new user" do
+ experiment = Multivariate::Experiment.find_or_create('link_color', 'blue', 'red')
+
+ previous_red_count = Multivariate::Alternative.find('red', 'link_color').participant_count
+ previous_blue_count = Multivariate::Alternative.find('blue', 'link_color').participant_count
+
+ Multivariate::Helper.ab_test('link_color', 'blue', 'red')
+
+ new_red_count = Multivariate::Alternative.find('red', 'link_color').participant_count
+ new_blue_count = Multivariate::Alternative.find('blue', 'link_color').participant_count
+
+ (new_red_count + new_blue_count).should eql(previous_red_count + previous_blue_count + 1)
+ end
+
+ it "should return the given alternative for an existing user" do
+ experiment = Multivariate::Experiment.find_or_create('link_color', 'blue', 'red')
+ alternative = Multivariate::Helper.ab_test('link_color', 'blue', 'red')
+ repeat_alternative = Multivariate::Helper.ab_test('link_color', 'blue', 'red')
+ alternative.should eql repeat_alternative
+ end
+ end
+end
\ No newline at end of file
| 40 | ab_test helper method implemented | 0 | .rb | rb | mit | splitrb/split |
10071898 | <NME> dashboard_spec.rb
<BEF> # frozen_string_literal: true
require "spec_helper"
require "rack/test"
require "split/dashboard"
describe Split::Dashboard do
include Rack::Test::Methods
class TestDashboard < Split::Dashboard
include Split::Helper
get "/my_experiment" do
ab_test(params[:experiment], "blue", "red")
end
end
def app
@app ||= TestDashboard
end
def link(color)
red = Split::Alternative.find('red', 'link_color')
blue = Split::Alternative.find('blue', 'link_color')
red.participant_count = 5
red.save
blue.participant_count = 6
blue.save
post '/reset/link_color'
let(:experiment_with_goals) {
Split::ExperimentCatalog.find_or_create({ "link_color" => ["goal_1", "goal_2"] }, "blue", "red")
}
let(:metric) {
Split::Metric.find_or_create(name: "testmetric", experiments: [experiment, experiment_with_goals])
}
let(:red_link) { link("red") }
let(:blue_link) { link("blue") }
before(:each) do
Split.configuration.beta_probability_simulations = 1
end
it "should respond to /" do
get "/"
expect(last_response).to be_ok
end
context "start experiment manually" do
before do
Split.configuration.start_manually = true
end
context "experiment without goals" do
it "should display a Start button" do
experiment
get "/"
expect(last_response.body).to include("Start")
post "/start?experiment=#{experiment.name}"
get "/"
expect(last_response.body).to include("Reset Data")
expect(last_response.body).not_to include("Metrics:")
end
end
context "experiment with metrics" do
it "should display the names of associated metrics" do
metric
get "/"
expect(last_response.body).to include("Metrics:testmetric")
end
end
context "with goals" do
it "should display a Start button" do
experiment_with_goals
get "/"
expect(last_response.body).to include("Start")
post "/start?experiment=#{experiment.name}"
get "/"
expect(last_response.body).to include("Reset Data")
end
end
end
describe "force alternative" do
context "initial version" do
let!(:user) do
Split::User.new(@app, { experiment.name => "red" })
end
before do
allow(Split::User).to receive(:new).and_return(user)
end
it "should set current user's alternative" do
blue_link.participant_count = 7
post "/force_alternative?experiment=#{experiment.name}", alternative: "blue"
get "/my_experiment?experiment=#{experiment.name}"
expect(last_response.body).to include("blue")
end
it "should not modify an existing user" do
blue_link.participant_count = 7
post "/force_alternative?experiment=#{experiment.name}", alternative: "blue"
expect(user[experiment.key]).to eq("red")
expect(blue_link.participant_count).to eq(7)
end
end
context "incremented version" do
let!(:user) do
experiment.increment_version
Split::User.new(@app, { "#{experiment.name}:#{experiment.version}" => "red" })
end
before do
allow(Split::User).to receive(:new).and_return(user)
end
it "should set current user's alternative" do
blue_link.participant_count = 7
post "/force_alternative?experiment=#{experiment.name}", alternative: "blue"
get "/my_experiment?experiment=#{experiment.name}"
expect(last_response.body).to include("blue")
end
end
end
describe "index page" do
context "with winner" do
before { experiment.winner = "red" }
it "displays `Reopen Experiment` button" do
get "/"
expect(last_response.body).to include("Reopen Experiment")
end
end
context "without winner" do
it "should not display `Reopen Experiment` button" do
get "/"
expect(last_response.body).to_not include("Reopen Experiment")
end
end
end
describe "reopen experiment" do
before { experiment.winner = "red" }
it "redirects" do
post "/reopen?experiment=#{experiment.name}"
expect(last_response).to be_redirect
end
it "removes winner" do
post "/reopen?experiment=#{experiment.name}"
expect(Split::ExperimentCatalog.find(experiment.name)).to_not have_winner
end
it "keeps existing stats" do
red_link.participant_count = 5
blue_link.participant_count = 7
experiment.winner = "blue"
post "/reopen?experiment=#{experiment.name}"
expect(red_link.participant_count).to eq(5)
expect(blue_link.participant_count).to eq(7)
end
end
describe "update cohorting" do
it "calls enable of cohorting when action is enable" do
post "/update_cohorting?experiment=#{experiment.name}", { "cohorting_action": "enable" }
expect(experiment.cohorting_disabled?).to eq false
end
it "calls disable of cohorting when action is disable" do
post "/update_cohorting?experiment=#{experiment.name}", { "cohorting_action": "disable" }
expect(experiment.cohorting_disabled?).to eq true
end
it "calls neither enable or disable cohorting when passed invalid action" do
previous_value = experiment.cohorting_disabled?
post "/update_cohorting?experiment=#{experiment.name}", { "cohorting_action": "other" }
expect(experiment.cohorting_disabled?).to eq previous_value
end
end
describe "initialize experiment" do
before do
Split.configuration.experiments = {
my_experiment: {
alternatives: [ "control", "alternative" ],
}
}
end
it "initializes the experiment when the experiment is given" do
expect(Split::ExperimentCatalog.find("my_experiment")).to be nil
post "/initialize_experiment", { experiment: "my_experiment" }
experiment = Split::ExperimentCatalog.find("my_experiment")
expect(experiment).to be_a(Split::Experiment)
end
it "does not attempt to intialize the experiment when empty experiment is given" do
post "/initialize_experiment", { experiment: "" }
expect(Split::ExperimentCatalog).to_not receive(:find_or_create)
end
it "does not attempt to intialize the experiment when no experiment is given" do
post "/initialize_experiment"
expect(Split::ExperimentCatalog).to_not receive(:find_or_create)
end
end
it "should reset an experiment" do
red_link.participant_count = 5
blue_link.participant_count = 7
experiment.winner = "blue"
post "/reset?experiment=#{experiment.name}"
expect(last_response).to be_redirect
new_red_count = red_link.participant_count
new_blue_count = blue_link.participant_count
expect(new_blue_count).to eq(0)
expect(new_red_count).to eq(0)
expect(experiment.winner).to be_nil
end
it "should delete an experiment" do
delete "/experiment?experiment=#{experiment.name}"
expect(last_response).to be_redirect
expect(Split::ExperimentCatalog.find(experiment.name)).to be_nil
end
it "should mark an alternative as the winner" do
expect(experiment.winner).to be_nil
post "/experiment?experiment=#{experiment.name}", alternative: "red"
expect(last_response).to be_redirect
expect(experiment.winner.name).to eq("red")
end
it "should display the start date" do
experiment.start
get "/"
expect(last_response.body).to include("<small>#{experiment.start_time.strftime('%Y-%m-%d')}</small>")
end
it "should handle experiments without a start date" do
Split.redis.hdel(:experiment_start_times, experiment.name)
get "/"
expect(last_response.body).to include("<small>Unknown</small>")
end
end
<MSG> Load participant count from Redis when necessary
<DFF> @@ -23,9 +23,7 @@ describe Split::Dashboard do
red = Split::Alternative.find('red', 'link_color')
blue = Split::Alternative.find('blue', 'link_color')
red.participant_count = 5
- red.save
blue.participant_count = 6
- blue.save
post '/reset/link_color'
| 0 | Load participant count from Redis when necessary | 2 | .rb | rb | mit | splitrb/split |
10071899 | <NME> dashboard_spec.rb
<BEF> # frozen_string_literal: true
require "spec_helper"
require "rack/test"
require "split/dashboard"
describe Split::Dashboard do
include Rack::Test::Methods
class TestDashboard < Split::Dashboard
include Split::Helper
get "/my_experiment" do
ab_test(params[:experiment], "blue", "red")
end
end
def app
@app ||= TestDashboard
end
def link(color)
red = Split::Alternative.find('red', 'link_color')
blue = Split::Alternative.find('blue', 'link_color')
red.participant_count = 5
red.save
blue.participant_count = 6
blue.save
post '/reset/link_color'
let(:experiment_with_goals) {
Split::ExperimentCatalog.find_or_create({ "link_color" => ["goal_1", "goal_2"] }, "blue", "red")
}
let(:metric) {
Split::Metric.find_or_create(name: "testmetric", experiments: [experiment, experiment_with_goals])
}
let(:red_link) { link("red") }
let(:blue_link) { link("blue") }
before(:each) do
Split.configuration.beta_probability_simulations = 1
end
it "should respond to /" do
get "/"
expect(last_response).to be_ok
end
context "start experiment manually" do
before do
Split.configuration.start_manually = true
end
context "experiment without goals" do
it "should display a Start button" do
experiment
get "/"
expect(last_response.body).to include("Start")
post "/start?experiment=#{experiment.name}"
get "/"
expect(last_response.body).to include("Reset Data")
expect(last_response.body).not_to include("Metrics:")
end
end
context "experiment with metrics" do
it "should display the names of associated metrics" do
metric
get "/"
expect(last_response.body).to include("Metrics:testmetric")
end
end
context "with goals" do
it "should display a Start button" do
experiment_with_goals
get "/"
expect(last_response.body).to include("Start")
post "/start?experiment=#{experiment.name}"
get "/"
expect(last_response.body).to include("Reset Data")
end
end
end
describe "force alternative" do
context "initial version" do
let!(:user) do
Split::User.new(@app, { experiment.name => "red" })
end
before do
allow(Split::User).to receive(:new).and_return(user)
end
it "should set current user's alternative" do
blue_link.participant_count = 7
post "/force_alternative?experiment=#{experiment.name}", alternative: "blue"
get "/my_experiment?experiment=#{experiment.name}"
expect(last_response.body).to include("blue")
end
it "should not modify an existing user" do
blue_link.participant_count = 7
post "/force_alternative?experiment=#{experiment.name}", alternative: "blue"
expect(user[experiment.key]).to eq("red")
expect(blue_link.participant_count).to eq(7)
end
end
context "incremented version" do
let!(:user) do
experiment.increment_version
Split::User.new(@app, { "#{experiment.name}:#{experiment.version}" => "red" })
end
before do
allow(Split::User).to receive(:new).and_return(user)
end
it "should set current user's alternative" do
blue_link.participant_count = 7
post "/force_alternative?experiment=#{experiment.name}", alternative: "blue"
get "/my_experiment?experiment=#{experiment.name}"
expect(last_response.body).to include("blue")
end
end
end
describe "index page" do
context "with winner" do
before { experiment.winner = "red" }
it "displays `Reopen Experiment` button" do
get "/"
expect(last_response.body).to include("Reopen Experiment")
end
end
context "without winner" do
it "should not display `Reopen Experiment` button" do
get "/"
expect(last_response.body).to_not include("Reopen Experiment")
end
end
end
describe "reopen experiment" do
before { experiment.winner = "red" }
it "redirects" do
post "/reopen?experiment=#{experiment.name}"
expect(last_response).to be_redirect
end
it "removes winner" do
post "/reopen?experiment=#{experiment.name}"
expect(Split::ExperimentCatalog.find(experiment.name)).to_not have_winner
end
it "keeps existing stats" do
red_link.participant_count = 5
blue_link.participant_count = 7
experiment.winner = "blue"
post "/reopen?experiment=#{experiment.name}"
expect(red_link.participant_count).to eq(5)
expect(blue_link.participant_count).to eq(7)
end
end
describe "update cohorting" do
it "calls enable of cohorting when action is enable" do
post "/update_cohorting?experiment=#{experiment.name}", { "cohorting_action": "enable" }
expect(experiment.cohorting_disabled?).to eq false
end
it "calls disable of cohorting when action is disable" do
post "/update_cohorting?experiment=#{experiment.name}", { "cohorting_action": "disable" }
expect(experiment.cohorting_disabled?).to eq true
end
it "calls neither enable or disable cohorting when passed invalid action" do
previous_value = experiment.cohorting_disabled?
post "/update_cohorting?experiment=#{experiment.name}", { "cohorting_action": "other" }
expect(experiment.cohorting_disabled?).to eq previous_value
end
end
describe "initialize experiment" do
before do
Split.configuration.experiments = {
my_experiment: {
alternatives: [ "control", "alternative" ],
}
}
end
it "initializes the experiment when the experiment is given" do
expect(Split::ExperimentCatalog.find("my_experiment")).to be nil
post "/initialize_experiment", { experiment: "my_experiment" }
experiment = Split::ExperimentCatalog.find("my_experiment")
expect(experiment).to be_a(Split::Experiment)
end
it "does not attempt to intialize the experiment when empty experiment is given" do
post "/initialize_experiment", { experiment: "" }
expect(Split::ExperimentCatalog).to_not receive(:find_or_create)
end
it "does not attempt to intialize the experiment when no experiment is given" do
post "/initialize_experiment"
expect(Split::ExperimentCatalog).to_not receive(:find_or_create)
end
end
it "should reset an experiment" do
red_link.participant_count = 5
blue_link.participant_count = 7
experiment.winner = "blue"
post "/reset?experiment=#{experiment.name}"
expect(last_response).to be_redirect
new_red_count = red_link.participant_count
new_blue_count = blue_link.participant_count
expect(new_blue_count).to eq(0)
expect(new_red_count).to eq(0)
expect(experiment.winner).to be_nil
end
it "should delete an experiment" do
delete "/experiment?experiment=#{experiment.name}"
expect(last_response).to be_redirect
expect(Split::ExperimentCatalog.find(experiment.name)).to be_nil
end
it "should mark an alternative as the winner" do
expect(experiment.winner).to be_nil
post "/experiment?experiment=#{experiment.name}", alternative: "red"
expect(last_response).to be_redirect
expect(experiment.winner.name).to eq("red")
end
it "should display the start date" do
experiment.start
get "/"
expect(last_response.body).to include("<small>#{experiment.start_time.strftime('%Y-%m-%d')}</small>")
end
it "should handle experiments without a start date" do
Split.redis.hdel(:experiment_start_times, experiment.name)
get "/"
expect(last_response.body).to include("<small>Unknown</small>")
end
end
<MSG> Load participant count from Redis when necessary
<DFF> @@ -23,9 +23,7 @@ describe Split::Dashboard do
red = Split::Alternative.find('red', 'link_color')
blue = Split::Alternative.find('blue', 'link_color')
red.participant_count = 5
- red.save
blue.participant_count = 6
- blue.save
post '/reset/link_color'
| 0 | Load participant count from Redis when necessary | 2 | .rb | rb | mit | splitrb/split |
10071900 | <NME> dashboard_spec.rb
<BEF> # frozen_string_literal: true
require "spec_helper"
require "rack/test"
require "split/dashboard"
describe Split::Dashboard do
include Rack::Test::Methods
class TestDashboard < Split::Dashboard
include Split::Helper
get "/my_experiment" do
ab_test(params[:experiment], "blue", "red")
end
end
def app
@app ||= TestDashboard
end
def link(color)
red = Split::Alternative.find('red', 'link_color')
blue = Split::Alternative.find('blue', 'link_color')
red.participant_count = 5
red.save
blue.participant_count = 6
blue.save
post '/reset/link_color'
let(:experiment_with_goals) {
Split::ExperimentCatalog.find_or_create({ "link_color" => ["goal_1", "goal_2"] }, "blue", "red")
}
let(:metric) {
Split::Metric.find_or_create(name: "testmetric", experiments: [experiment, experiment_with_goals])
}
let(:red_link) { link("red") }
let(:blue_link) { link("blue") }
before(:each) do
Split.configuration.beta_probability_simulations = 1
end
it "should respond to /" do
get "/"
expect(last_response).to be_ok
end
context "start experiment manually" do
before do
Split.configuration.start_manually = true
end
context "experiment without goals" do
it "should display a Start button" do
experiment
get "/"
expect(last_response.body).to include("Start")
post "/start?experiment=#{experiment.name}"
get "/"
expect(last_response.body).to include("Reset Data")
expect(last_response.body).not_to include("Metrics:")
end
end
context "experiment with metrics" do
it "should display the names of associated metrics" do
metric
get "/"
expect(last_response.body).to include("Metrics:testmetric")
end
end
context "with goals" do
it "should display a Start button" do
experiment_with_goals
get "/"
expect(last_response.body).to include("Start")
post "/start?experiment=#{experiment.name}"
get "/"
expect(last_response.body).to include("Reset Data")
end
end
end
describe "force alternative" do
context "initial version" do
let!(:user) do
Split::User.new(@app, { experiment.name => "red" })
end
before do
allow(Split::User).to receive(:new).and_return(user)
end
it "should set current user's alternative" do
blue_link.participant_count = 7
post "/force_alternative?experiment=#{experiment.name}", alternative: "blue"
get "/my_experiment?experiment=#{experiment.name}"
expect(last_response.body).to include("blue")
end
it "should not modify an existing user" do
blue_link.participant_count = 7
post "/force_alternative?experiment=#{experiment.name}", alternative: "blue"
expect(user[experiment.key]).to eq("red")
expect(blue_link.participant_count).to eq(7)
end
end
context "incremented version" do
let!(:user) do
experiment.increment_version
Split::User.new(@app, { "#{experiment.name}:#{experiment.version}" => "red" })
end
before do
allow(Split::User).to receive(:new).and_return(user)
end
it "should set current user's alternative" do
blue_link.participant_count = 7
post "/force_alternative?experiment=#{experiment.name}", alternative: "blue"
get "/my_experiment?experiment=#{experiment.name}"
expect(last_response.body).to include("blue")
end
end
end
describe "index page" do
context "with winner" do
before { experiment.winner = "red" }
it "displays `Reopen Experiment` button" do
get "/"
expect(last_response.body).to include("Reopen Experiment")
end
end
context "without winner" do
it "should not display `Reopen Experiment` button" do
get "/"
expect(last_response.body).to_not include("Reopen Experiment")
end
end
end
describe "reopen experiment" do
before { experiment.winner = "red" }
it "redirects" do
post "/reopen?experiment=#{experiment.name}"
expect(last_response).to be_redirect
end
it "removes winner" do
post "/reopen?experiment=#{experiment.name}"
expect(Split::ExperimentCatalog.find(experiment.name)).to_not have_winner
end
it "keeps existing stats" do
red_link.participant_count = 5
blue_link.participant_count = 7
experiment.winner = "blue"
post "/reopen?experiment=#{experiment.name}"
expect(red_link.participant_count).to eq(5)
expect(blue_link.participant_count).to eq(7)
end
end
describe "update cohorting" do
it "calls enable of cohorting when action is enable" do
post "/update_cohorting?experiment=#{experiment.name}", { "cohorting_action": "enable" }
expect(experiment.cohorting_disabled?).to eq false
end
it "calls disable of cohorting when action is disable" do
post "/update_cohorting?experiment=#{experiment.name}", { "cohorting_action": "disable" }
expect(experiment.cohorting_disabled?).to eq true
end
it "calls neither enable or disable cohorting when passed invalid action" do
previous_value = experiment.cohorting_disabled?
post "/update_cohorting?experiment=#{experiment.name}", { "cohorting_action": "other" }
expect(experiment.cohorting_disabled?).to eq previous_value
end
end
describe "initialize experiment" do
before do
Split.configuration.experiments = {
my_experiment: {
alternatives: [ "control", "alternative" ],
}
}
end
it "initializes the experiment when the experiment is given" do
expect(Split::ExperimentCatalog.find("my_experiment")).to be nil
post "/initialize_experiment", { experiment: "my_experiment" }
experiment = Split::ExperimentCatalog.find("my_experiment")
expect(experiment).to be_a(Split::Experiment)
end
it "does not attempt to intialize the experiment when empty experiment is given" do
post "/initialize_experiment", { experiment: "" }
expect(Split::ExperimentCatalog).to_not receive(:find_or_create)
end
it "does not attempt to intialize the experiment when no experiment is given" do
post "/initialize_experiment"
expect(Split::ExperimentCatalog).to_not receive(:find_or_create)
end
end
it "should reset an experiment" do
red_link.participant_count = 5
blue_link.participant_count = 7
experiment.winner = "blue"
post "/reset?experiment=#{experiment.name}"
expect(last_response).to be_redirect
new_red_count = red_link.participant_count
new_blue_count = blue_link.participant_count
expect(new_blue_count).to eq(0)
expect(new_red_count).to eq(0)
expect(experiment.winner).to be_nil
end
it "should delete an experiment" do
delete "/experiment?experiment=#{experiment.name}"
expect(last_response).to be_redirect
expect(Split::ExperimentCatalog.find(experiment.name)).to be_nil
end
it "should mark an alternative as the winner" do
expect(experiment.winner).to be_nil
post "/experiment?experiment=#{experiment.name}", alternative: "red"
expect(last_response).to be_redirect
expect(experiment.winner.name).to eq("red")
end
it "should display the start date" do
experiment.start
get "/"
expect(last_response.body).to include("<small>#{experiment.start_time.strftime('%Y-%m-%d')}</small>")
end
it "should handle experiments without a start date" do
Split.redis.hdel(:experiment_start_times, experiment.name)
get "/"
expect(last_response.body).to include("<small>Unknown</small>")
end
end
<MSG> Load participant count from Redis when necessary
<DFF> @@ -23,9 +23,7 @@ describe Split::Dashboard do
red = Split::Alternative.find('red', 'link_color')
blue = Split::Alternative.find('blue', 'link_color')
red.participant_count = 5
- red.save
blue.participant_count = 6
- blue.save
post '/reset/link_color'
| 0 | Load participant count from Redis when necessary | 2 | .rb | rb | mit | splitrb/split |
10071901 | <NME> split.gemspec
<BEF> # -*- encoding: utf-8 -*-
# frozen_string_literal: true
$:.push File.expand_path("../lib", __FILE__)
require "split/version"
Gem::Specification.new do |s|
s.name = "split"
s.version = Split::VERSION
s.platform = Gem::Platform::RUBY
s.authors = ["Andrew Nesbitt"]
s.licenses = ["MIT"]
s.email = ["[email protected]"]
s.homepage = "https://github.com/splitrb/split"
s.summary = "Rack based split testing framework"
s.metadata = {
"homepage_uri" => "https://github.com/splitrb/split",
"changelog_uri" => "https://github.com/splitrb/split/blob/main/CHANGELOG.md",
"source_code_uri" => "https://github.com/splitrb/split",
"bug_tracker_uri" => "https://github.com/splitrb/split/issues",
"wiki_uri" => "https://github.com/splitrb/split/wiki",
"mailing_list_uri" => "https://groups.google.com/d/forum/split-ruby"
}
s.required_ruby_version = ">= 2.5.0"
s.required_rubygems_version = ">= 2.0.0"
s.files = `git ls-files`.split("\n")
s.test_files = `git ls-files -- {test,spec,features}/*`.split("\n")
s.require_paths = ["lib"]
s.add_development_dependency 'bundler', '~> 1.0'
s.add_development_dependency 'rspec', '~> 2.12'
s.add_development_dependency 'rack-test', '~> 0.6'
s.add_development_dependency 'pry'
s.add_development_dependency 'pry-debugger'
end
s.add_development_dependency "bundler", ">= 1.17"
s.add_development_dependency "simplecov", "~> 0.15"
s.add_development_dependency "rack-test", "~> 2.0"
s.add_development_dependency "rake", "~> 13"
s.add_development_dependency "rspec", "~> 3.7"
s.add_development_dependency "pry", "~> 0.10"
s.add_development_dependency "rails", ">= 5.0"
end
<MSG> support ruby 1.8.7.
<DFF> @@ -32,6 +32,4 @@ Gem::Specification.new do |s|
s.add_development_dependency 'bundler', '~> 1.0'
s.add_development_dependency 'rspec', '~> 2.12'
s.add_development_dependency 'rack-test', '~> 0.6'
- s.add_development_dependency 'pry'
- s.add_development_dependency 'pry-debugger'
end
| 0 | support ruby 1.8.7. | 2 | .gemspec | gemspec | mit | splitrb/split |
10071902 | <NME> split.gemspec
<BEF> # -*- encoding: utf-8 -*-
# frozen_string_literal: true
$:.push File.expand_path("../lib", __FILE__)
require "split/version"
Gem::Specification.new do |s|
s.name = "split"
s.version = Split::VERSION
s.platform = Gem::Platform::RUBY
s.authors = ["Andrew Nesbitt"]
s.licenses = ["MIT"]
s.email = ["[email protected]"]
s.homepage = "https://github.com/splitrb/split"
s.summary = "Rack based split testing framework"
s.metadata = {
"homepage_uri" => "https://github.com/splitrb/split",
"changelog_uri" => "https://github.com/splitrb/split/blob/main/CHANGELOG.md",
"source_code_uri" => "https://github.com/splitrb/split",
"bug_tracker_uri" => "https://github.com/splitrb/split/issues",
"wiki_uri" => "https://github.com/splitrb/split/wiki",
"mailing_list_uri" => "https://groups.google.com/d/forum/split-ruby"
}
s.required_ruby_version = ">= 2.5.0"
s.required_rubygems_version = ">= 2.0.0"
s.files = `git ls-files`.split("\n")
s.test_files = `git ls-files -- {test,spec,features}/*`.split("\n")
s.require_paths = ["lib"]
s.add_development_dependency 'bundler', '~> 1.0'
s.add_development_dependency 'rspec', '~> 2.12'
s.add_development_dependency 'rack-test', '~> 0.6'
s.add_development_dependency 'pry'
s.add_development_dependency 'pry-debugger'
end
s.add_development_dependency "bundler", ">= 1.17"
s.add_development_dependency "simplecov", "~> 0.15"
s.add_development_dependency "rack-test", "~> 2.0"
s.add_development_dependency "rake", "~> 13"
s.add_development_dependency "rspec", "~> 3.7"
s.add_development_dependency "pry", "~> 0.10"
s.add_development_dependency "rails", ">= 5.0"
end
<MSG> support ruby 1.8.7.
<DFF> @@ -32,6 +32,4 @@ Gem::Specification.new do |s|
s.add_development_dependency 'bundler', '~> 1.0'
s.add_development_dependency 'rspec', '~> 2.12'
s.add_development_dependency 'rack-test', '~> 0.6'
- s.add_development_dependency 'pry'
- s.add_development_dependency 'pry-debugger'
end
| 0 | support ruby 1.8.7. | 2 | .gemspec | gemspec | mit | splitrb/split |
10071903 | <NME> split.gemspec
<BEF> # -*- encoding: utf-8 -*-
# frozen_string_literal: true
$:.push File.expand_path("../lib", __FILE__)
require "split/version"
Gem::Specification.new do |s|
s.name = "split"
s.version = Split::VERSION
s.platform = Gem::Platform::RUBY
s.authors = ["Andrew Nesbitt"]
s.licenses = ["MIT"]
s.email = ["[email protected]"]
s.homepage = "https://github.com/splitrb/split"
s.summary = "Rack based split testing framework"
s.metadata = {
"homepage_uri" => "https://github.com/splitrb/split",
"changelog_uri" => "https://github.com/splitrb/split/blob/main/CHANGELOG.md",
"source_code_uri" => "https://github.com/splitrb/split",
"bug_tracker_uri" => "https://github.com/splitrb/split/issues",
"wiki_uri" => "https://github.com/splitrb/split/wiki",
"mailing_list_uri" => "https://groups.google.com/d/forum/split-ruby"
}
s.required_ruby_version = ">= 2.5.0"
s.required_rubygems_version = ">= 2.0.0"
s.files = `git ls-files`.split("\n")
s.test_files = `git ls-files -- {test,spec,features}/*`.split("\n")
s.require_paths = ["lib"]
s.add_development_dependency 'bundler', '~> 1.0'
s.add_development_dependency 'rspec', '~> 2.12'
s.add_development_dependency 'rack-test', '~> 0.6'
s.add_development_dependency 'pry'
s.add_development_dependency 'pry-debugger'
end
s.add_development_dependency "bundler", ">= 1.17"
s.add_development_dependency "simplecov", "~> 0.15"
s.add_development_dependency "rack-test", "~> 2.0"
s.add_development_dependency "rake", "~> 13"
s.add_development_dependency "rspec", "~> 3.7"
s.add_development_dependency "pry", "~> 0.10"
s.add_development_dependency "rails", ">= 5.0"
end
<MSG> support ruby 1.8.7.
<DFF> @@ -32,6 +32,4 @@ Gem::Specification.new do |s|
s.add_development_dependency 'bundler', '~> 1.0'
s.add_development_dependency 'rspec', '~> 2.12'
s.add_development_dependency 'rack-test', '~> 0.6'
- s.add_development_dependency 'pry'
- s.add_development_dependency 'pry-debugger'
end
| 0 | support ruby 1.8.7. | 2 | .gemspec | gemspec | mit | splitrb/split |
10071904 | <NME> split.rb
<BEF> # frozen_string_literal: true
require "redis"
require "split/algorithms"
require "split/algorithms/block_randomization"
require "split/algorithms/weighted_sample"
require "split/algorithms/whiplash"
require "split/alternative"
require "split/cache"
require "split/configuration"
require "split/encapsulated_helper"
require "split/exceptions"
require "split/experiment"
require "split/experiment_catalog"
require "split/extensions/string"
require "split/goals_collection"
require "split/helper"
require "split/combined_experiments_helper"
require "split/metric"
require "split/persistence"
require "split/redis_interface"
require "split/trial"
require "split/user"
require "split/version"
require "split/zscore"
require "split/engine" if defined?(Rails)
module Split
extend self
attr_accessor :configuration
# Accepts:
# 1. A redis URL (valid for `Redis.new(url: url)`)
# `Redis::DistRedis`, or `Redis::Namespace`.
def redis=(server)
@redis = if server.is_a?(String)
Redis.new(:url => server, :thread_safe => true)
elsif server.is_a?(Hash)
Redis.new(server.merge(:thread_safe => true))
elsif server.respond_to?(:smembers)
server
else
elsif server.respond_to?(:smembers)
server
else
raise ArgumentError,
"You must supply a url, options hash or valid Redis connection instance"
end
end
# Returns the current Redis connection. If none has been created, will
# create a new one.
def redis
return @redis if @redis
self.redis = self.configuration.redis
self.redis
end
# Call this method to modify defaults in your initializers.
#
# @example
# Split.configure do |config|
# config.ignore_ip_addresses = '192.168.2.1'
# end
def configure
self.configuration ||= Configuration.new
yield(configuration)
end
def cache(namespace, key, &block)
Split::Cache.fetch(namespace, key, &block)
end
end
# Check to see if being run in a Rails application. If so, wait until before_initialize to run configuration so Gems that create ENV variables have the chance to initialize first.
if defined?(::Rails)
class Split::Railtie < Rails::Railtie
config.before_initialize { Split.configure { } }
end
else
Split.configure { }
end
<MSG> Merge pull request #630 from splitrb/remove-old-redis-config
Remove thread_safe config as redis-rb is thread_safe by default since 2.2
<DFF> @@ -35,9 +35,9 @@ module Split
# `Redis::DistRedis`, or `Redis::Namespace`.
def redis=(server)
@redis = if server.is_a?(String)
- Redis.new(:url => server, :thread_safe => true)
+ Redis.new(url: server)
elsif server.is_a?(Hash)
- Redis.new(server.merge(:thread_safe => true))
+ Redis.new(server)
elsif server.respond_to?(:smembers)
server
else
| 2 | Merge pull request #630 from splitrb/remove-old-redis-config | 2 | .rb | rb | mit | splitrb/split |
10071905 | <NME> split.rb
<BEF> # frozen_string_literal: true
require "redis"
require "split/algorithms"
require "split/algorithms/block_randomization"
require "split/algorithms/weighted_sample"
require "split/algorithms/whiplash"
require "split/alternative"
require "split/cache"
require "split/configuration"
require "split/encapsulated_helper"
require "split/exceptions"
require "split/experiment"
require "split/experiment_catalog"
require "split/extensions/string"
require "split/goals_collection"
require "split/helper"
require "split/combined_experiments_helper"
require "split/metric"
require "split/persistence"
require "split/redis_interface"
require "split/trial"
require "split/user"
require "split/version"
require "split/zscore"
require "split/engine" if defined?(Rails)
module Split
extend self
attr_accessor :configuration
# Accepts:
# 1. A redis URL (valid for `Redis.new(url: url)`)
# `Redis::DistRedis`, or `Redis::Namespace`.
def redis=(server)
@redis = if server.is_a?(String)
Redis.new(:url => server, :thread_safe => true)
elsif server.is_a?(Hash)
Redis.new(server.merge(:thread_safe => true))
elsif server.respond_to?(:smembers)
server
else
elsif server.respond_to?(:smembers)
server
else
raise ArgumentError,
"You must supply a url, options hash or valid Redis connection instance"
end
end
# Returns the current Redis connection. If none has been created, will
# create a new one.
def redis
return @redis if @redis
self.redis = self.configuration.redis
self.redis
end
# Call this method to modify defaults in your initializers.
#
# @example
# Split.configure do |config|
# config.ignore_ip_addresses = '192.168.2.1'
# end
def configure
self.configuration ||= Configuration.new
yield(configuration)
end
def cache(namespace, key, &block)
Split::Cache.fetch(namespace, key, &block)
end
end
# Check to see if being run in a Rails application. If so, wait until before_initialize to run configuration so Gems that create ENV variables have the chance to initialize first.
if defined?(::Rails)
class Split::Railtie < Rails::Railtie
config.before_initialize { Split.configure { } }
end
else
Split.configure { }
end
<MSG> Merge pull request #630 from splitrb/remove-old-redis-config
Remove thread_safe config as redis-rb is thread_safe by default since 2.2
<DFF> @@ -35,9 +35,9 @@ module Split
# `Redis::DistRedis`, or `Redis::Namespace`.
def redis=(server)
@redis = if server.is_a?(String)
- Redis.new(:url => server, :thread_safe => true)
+ Redis.new(url: server)
elsif server.is_a?(Hash)
- Redis.new(server.merge(:thread_safe => true))
+ Redis.new(server)
elsif server.respond_to?(:smembers)
server
else
| 2 | Merge pull request #630 from splitrb/remove-old-redis-config | 2 | .rb | rb | mit | splitrb/split |
10071906 | <NME> split.rb
<BEF> # frozen_string_literal: true
require "redis"
require "split/algorithms"
require "split/algorithms/block_randomization"
require "split/algorithms/weighted_sample"
require "split/algorithms/whiplash"
require "split/alternative"
require "split/cache"
require "split/configuration"
require "split/encapsulated_helper"
require "split/exceptions"
require "split/experiment"
require "split/experiment_catalog"
require "split/extensions/string"
require "split/goals_collection"
require "split/helper"
require "split/combined_experiments_helper"
require "split/metric"
require "split/persistence"
require "split/redis_interface"
require "split/trial"
require "split/user"
require "split/version"
require "split/zscore"
require "split/engine" if defined?(Rails)
module Split
extend self
attr_accessor :configuration
# Accepts:
# 1. A redis URL (valid for `Redis.new(url: url)`)
# `Redis::DistRedis`, or `Redis::Namespace`.
def redis=(server)
@redis = if server.is_a?(String)
Redis.new(:url => server, :thread_safe => true)
elsif server.is_a?(Hash)
Redis.new(server.merge(:thread_safe => true))
elsif server.respond_to?(:smembers)
server
else
elsif server.respond_to?(:smembers)
server
else
raise ArgumentError,
"You must supply a url, options hash or valid Redis connection instance"
end
end
# Returns the current Redis connection. If none has been created, will
# create a new one.
def redis
return @redis if @redis
self.redis = self.configuration.redis
self.redis
end
# Call this method to modify defaults in your initializers.
#
# @example
# Split.configure do |config|
# config.ignore_ip_addresses = '192.168.2.1'
# end
def configure
self.configuration ||= Configuration.new
yield(configuration)
end
def cache(namespace, key, &block)
Split::Cache.fetch(namespace, key, &block)
end
end
# Check to see if being run in a Rails application. If so, wait until before_initialize to run configuration so Gems that create ENV variables have the chance to initialize first.
if defined?(::Rails)
class Split::Railtie < Rails::Railtie
config.before_initialize { Split.configure { } }
end
else
Split.configure { }
end
<MSG> Merge pull request #630 from splitrb/remove-old-redis-config
Remove thread_safe config as redis-rb is thread_safe by default since 2.2
<DFF> @@ -35,9 +35,9 @@ module Split
# `Redis::DistRedis`, or `Redis::Namespace`.
def redis=(server)
@redis = if server.is_a?(String)
- Redis.new(:url => server, :thread_safe => true)
+ Redis.new(url: server)
elsif server.is_a?(Hash)
- Redis.new(server.merge(:thread_safe => true))
+ Redis.new(server)
elsif server.respond_to?(:smembers)
server
else
| 2 | Merge pull request #630 from splitrb/remove-old-redis-config | 2 | .rb | rb | mit | splitrb/split |
10071907 | <NME> stylesheet.ts
<BEF> import { strictEqual as equal } from 'assert';
import { stylesheet as expandAbbreviation, parseStylesheetSnippets, resolveConfig } from '../src';
const defaultConfig = resolveConfig({
type: 'stylesheet',
options: {
'output.field': (index, placeholder) => `\${${index}${placeholder ? ':' + placeholder : ''}}`,
'stylesheet.fuzzySearchMinScore': 0
},
snippets: {
mten: 'margin: 10px;',
fsz: 'font-size',
gt: 'grid-template: repeat(2,auto) / repeat(auto-fit, minmax(250px, 1fr))'
},
cache: {},
});
}
describe('Stylesheet abbreviations', () => {
it('keywords', () => {
equal(expand('bd1-s'), 'border: 1px solid;');
equal(expand('dib'), 'display: inline-block;');
it('keywords', () => {
equal(expand('bd1-s'), 'border: 1px solid;');
equal(expand('dib'), 'display: inline-block;');
equal(expand('bxsz'), 'box-sizing: ${1:border-box};');
equal(expand('bxz'), 'box-sizing: ${1:border-box};');
equal(expand('bxzc'), 'box-sizing: content-box;');
equal(expand('fl'), 'float: ${1:left};');
equal(expand('fll'), 'float: left;');
equal(expand('pos'), 'position: ${1:relative};');
equal(expand('poa'), 'position: absolute;');
equal(expand('por'), 'position: relative;');
equal(expand('pof'), 'position: fixed;');
equal(expand('pos-a'), 'position: absolute;');
equal(expand('m'), 'margin: ${0};');
equal(expand('m0'), 'margin: 0;');
// use `auto` as global keyword
equal(expand('m0-a'), 'margin: 0 auto;');
equal(expand('m-a'), 'margin: auto;');
equal(expand('bg'), 'background: ${1:#000};');
equal(expand('bd'), 'border: ${1:1px} ${2:solid} ${3:#000};');
equal(expand('bd0-s#fc0'), 'border: 0 solid #fc0;');
equal(expand('bd0-dd#fc0'), 'border: 0 dot-dash #fc0;');
equal(expand('bd0-h#fc0'), 'border: 0 hidden #fc0;');
equal(expand('trf-trs'), 'transform: translate(${1:x}, ${2:y});');
// https://github.com/emmetio/emmet/issues/610
equal(expand('c'), 'color: ${1:#000};');
equal(expand('cr'), 'color: rgb(${1:0}, ${2:0}, ${3:0});');
equal(expand('cra'), 'color: rgba(${1:0}, ${2:0}, ${3:0}, ${4:.5});');
// https://github.com/emmetio/emmet/issues/647
equal(expand('gtc'), 'grid-template-columns: repeat(${0});');
equal(expand('gtr'), 'grid-template-rows: repeat(${0});');
equal(expand('lis:n'), 'list-style: none;');
equal(expand('list:n'), 'list-style-type: none;');
equal(expand('bdt:n'), 'border-top: none;');
equal(expand('bgi:n'), 'background-image: none;');
equal(expand('q:n'), 'quotes: none;');
});
it('numeric', () => {
equal(expand('p0'), 'padding: 0;', 'No unit for 0');
equal(expand('p10'), 'padding: 10px;', '`px` unit for integers');
equal(expand('p.4'), 'padding: 0.4em;', '`em` for floats');
equal(expand('fz10'), 'font-size: 10px;', '`px` for integers');
equal(expand('fz1.'), 'font-size: 1em;', '`em` for explicit float');
equal(expand('p10p'), 'padding: 10%;', 'unit alias');
equal(expand('z10'), 'z-index: 10;', 'Unitless property');
equal(expand('p10r'), 'padding: 10rem;', 'unit alias');
equal(expand('mten'), 'margin: 10px;', 'Ignore terminating `;` in snippet');
// https://github.com/microsoft/vscode/issues/59951
equal(expand('fz'), 'font-size: ${0};');
equal(expand('fz12'), 'font-size: 12px;');
equal(expand('fsz'), 'font-size: ${0};');
equal(expand('fsz12'), 'font-size: 12px;');
equal(expand('fs'), 'font-style: ${1:italic};');
// https://github.com/emmetio/emmet/issues/558
equal(expand('us'), 'user-select: none;');
// https://github.com/microsoft/vscode/issues/105697
equal(expand('opa1'), 'opacity: 1;', 'Unitless property');
equal(expand('opa.1'), 'opacity: 0.1;', 'Unitless property');
equal(expand('opa.a'), 'opacity: .a;', 'Unitless property');
});
it('numeric with format options', () => {
const config = resolveConfig({
type: 'stylesheet',
options: {
'stylesheet.intUnit': 'pt',
'stylesheet.floatUnit': 'vh',
'stylesheet.unitAliases': {
e: 'em',
p: '%',
x: 'ex',
r: ' / @rem'
}
}
});
equal(expand('p0', config), 'padding: 0;', 'No unit for 0');
equal(expand('p10', config), 'padding: 10pt;', '`pt` unit for integers');
equal(expand('p.4', config), 'padding: 0.4vh;', '`vh` for floats');
equal(expand('p10p', config), 'padding: 10%;', 'unit alias');
equal(expand('z10', config), 'z-index: 10;', 'Unitless property');
equal(expand('p10r', config), 'padding: 10 / @rem;', 'unit alias');
});
it('important', () => {
equal(expand('!'), '!important');
equal(expand('p!'), 'padding: ${0} !important;');
equal(expand('p0!'), 'padding: 0 !important;');
});
it('color', () => {
equal(expand('c'), 'color: ${1:#000};');
equal(expand('c#'), 'color: #000;');
equal(expand('c#f.5'), 'color: rgba(255, 255, 255, 0.5);');
equal(expand('c#f.5!'), 'color: rgba(255, 255, 255, 0.5) !important;');
equal(expand('bgc'), 'background-color: #${1:fff};');
});
it('snippets', () => {
equal(expand('@'), '@media ${1:screen} {\n\t${0}\n}');
// Insert value into snippet fields
equal(expand('@k-name'), '@keyframes name {\n\t${2}\n}');
equal(expand('@k-name10'), '@keyframes name {\n\t10\n}');
equal(expand('gt'), 'grid-template: repeat(2, auto) / repeat(auto-fit, minmax(250px, 1fr));');
});
it('multiple properties', () => {
equal(expand('p10+m10-20'), 'padding: 10px;\nmargin: 10px 20px;');
equal(expand('p+bd'), 'padding: ${0};\nborder: ${1:1px} ${2:solid} ${3:#000};');
});
it('functions', () => {
equal(expand('trf-s(2)'), 'transform: scale(2, ${2:y});');
equal(expand('trf-s(2, 3)'), 'transform: scale(2, 3);');
});
it('case insensitive matches', () => {
equal(expand('trf:rx'), 'transform: rotateX(${1:angle});');
});
it('gradient resolver', () => {
equal(expand('lg'), 'background-image: linear-gradient(${0});');
equal(expand('lg(to right, #0, #f00.5)'), 'background-image: linear-gradient(to right, #000, rgba(255, 0, 0, 0.5));');
});
it('unmatched abbreviation', () => {
// This example is useless: it’s unexpected to receive `align-self: unset`
// for `auto` snippet
// equal(expand('auto', resolveConfig({
// type: 'stylesheet',
// options: { 'stylesheet.fuzzySearchMinScore': 0 }
// })), 'align-self: unset;');
equal(expand('auto'), 'auto: ${0};');
});
it('CSS-in-JS', () => {
const config = resolveConfig({
type: 'stylesheet',
options: {
'stylesheet.json': true,
'stylesheet.between': ': '
}
});
equal(expand('p10+mt10-20', config), 'padding: 10,\nmarginTop: \'10px 20px\',');
equal(expand('bgc', config), 'backgroundColor: \'#fff\',');
});
it('resolve context value', () => {
const config = resolveConfig({
type: 'stylesheet',
context: { name: 'align-content' }
});
equal(expand('s', config), 'start');
equal(expand('a', config), 'auto');
});
it('limit snippets by scope', () => {
const sectionScope = resolveConfig({
type: 'stylesheet',
context: { name: CSSAbbreviationScope.Section },
snippets: {
mten: 'margin: 10px;',
fsz: 'font-size',
myCenterAwesome: 'body {\n\tdisplay: grid;\n}'
}
});
const propertyScope = resolveConfig({
type: 'stylesheet',
context: { name: CSSAbbreviationScope.Property },
snippets: {
mten: 'margin: 10px;',
fsz: 'font-size',
myCenterAwesome: 'body {\n\tdisplay: grid;\n}'
}
});
equal(expand('m', sectionScope), 'body {\n\tdisplay: grid;\n}');
equal(expand('b', sectionScope), '');
equal(expand('m', propertyScope), 'margin: ;');
});
});
<MSG> Added scoring tests
<DFF> @@ -1,5 +1,6 @@
-import { strictEqual as equal } from 'assert';
+import { strictEqual as equal, ok } from 'assert';
import { stylesheet as expandAbbreviation, parseStylesheetSnippets, resolveConfig } from '../src';
+import score from '../src/stylesheet/score';
const defaultConfig = resolveConfig({
type: 'stylesheet',
@@ -17,6 +18,36 @@ function expand(abbr: string, config = defaultConfig) {
}
describe('Stylesheet abbreviations', () => {
+ describe('Scoring', () => {
+ const pick = (abbr: string, items: string[]) => items
+ .map(item => ({ item, score: score(abbr, item) }))
+ .filter(obj => obj.score)
+ .sort((a, b) => b.score - a.score)
+ .map(obj => obj.item)[0];
+
+ it('compare scores', () => {
+ equal(score('aaa', 'aaa'), 1);
+ equal(score('baa', 'aaa'), 0);
+
+ ok(!score('b', 'aaa'));
+ ok(score('a', 'aaa'));
+ ok(score('a', 'abc'));
+ ok(score('ac', 'abc'));
+ ok(score('a', 'aaa') < score('aa', 'aaa'));
+ ok(score('ab', 'abc') > score('ab', 'acb'));
+
+ // acronym bonus
+ ok(score('ab', 'a-b') > score('ab', 'acb'));
+ });
+
+ it('pick padding or position', () => {
+ const items = ['p', 'pb', 'pl', 'pos', 'pa', 'oa', 'soa', 'pr', 'pt'];
+
+ equal(pick('p', items), 'p');
+ equal(pick('poa', items), 'pos');
+ });
+ });
+
it('keywords', () => {
equal(expand('bd1-s'), 'border: 1px solid;');
equal(expand('dib'), 'display: inline-block;');
| 32 | Added scoring tests | 1 | .ts | ts | mit | emmetio/emmet |
10071908 | <NME> stylesheet.ts
<BEF> import { strictEqual as equal } from 'assert';
import { stylesheet as expandAbbreviation, parseStylesheetSnippets, resolveConfig } from '../src';
const defaultConfig = resolveConfig({
type: 'stylesheet',
options: {
'output.field': (index, placeholder) => `\${${index}${placeholder ? ':' + placeholder : ''}}`,
'stylesheet.fuzzySearchMinScore': 0
},
snippets: {
mten: 'margin: 10px;',
fsz: 'font-size',
gt: 'grid-template: repeat(2,auto) / repeat(auto-fit, minmax(250px, 1fr))'
},
cache: {},
});
}
describe('Stylesheet abbreviations', () => {
it('keywords', () => {
equal(expand('bd1-s'), 'border: 1px solid;');
equal(expand('dib'), 'display: inline-block;');
it('keywords', () => {
equal(expand('bd1-s'), 'border: 1px solid;');
equal(expand('dib'), 'display: inline-block;');
equal(expand('bxsz'), 'box-sizing: ${1:border-box};');
equal(expand('bxz'), 'box-sizing: ${1:border-box};');
equal(expand('bxzc'), 'box-sizing: content-box;');
equal(expand('fl'), 'float: ${1:left};');
equal(expand('fll'), 'float: left;');
equal(expand('pos'), 'position: ${1:relative};');
equal(expand('poa'), 'position: absolute;');
equal(expand('por'), 'position: relative;');
equal(expand('pof'), 'position: fixed;');
equal(expand('pos-a'), 'position: absolute;');
equal(expand('m'), 'margin: ${0};');
equal(expand('m0'), 'margin: 0;');
// use `auto` as global keyword
equal(expand('m0-a'), 'margin: 0 auto;');
equal(expand('m-a'), 'margin: auto;');
equal(expand('bg'), 'background: ${1:#000};');
equal(expand('bd'), 'border: ${1:1px} ${2:solid} ${3:#000};');
equal(expand('bd0-s#fc0'), 'border: 0 solid #fc0;');
equal(expand('bd0-dd#fc0'), 'border: 0 dot-dash #fc0;');
equal(expand('bd0-h#fc0'), 'border: 0 hidden #fc0;');
equal(expand('trf-trs'), 'transform: translate(${1:x}, ${2:y});');
// https://github.com/emmetio/emmet/issues/610
equal(expand('c'), 'color: ${1:#000};');
equal(expand('cr'), 'color: rgb(${1:0}, ${2:0}, ${3:0});');
equal(expand('cra'), 'color: rgba(${1:0}, ${2:0}, ${3:0}, ${4:.5});');
// https://github.com/emmetio/emmet/issues/647
equal(expand('gtc'), 'grid-template-columns: repeat(${0});');
equal(expand('gtr'), 'grid-template-rows: repeat(${0});');
equal(expand('lis:n'), 'list-style: none;');
equal(expand('list:n'), 'list-style-type: none;');
equal(expand('bdt:n'), 'border-top: none;');
equal(expand('bgi:n'), 'background-image: none;');
equal(expand('q:n'), 'quotes: none;');
});
it('numeric', () => {
equal(expand('p0'), 'padding: 0;', 'No unit for 0');
equal(expand('p10'), 'padding: 10px;', '`px` unit for integers');
equal(expand('p.4'), 'padding: 0.4em;', '`em` for floats');
equal(expand('fz10'), 'font-size: 10px;', '`px` for integers');
equal(expand('fz1.'), 'font-size: 1em;', '`em` for explicit float');
equal(expand('p10p'), 'padding: 10%;', 'unit alias');
equal(expand('z10'), 'z-index: 10;', 'Unitless property');
equal(expand('p10r'), 'padding: 10rem;', 'unit alias');
equal(expand('mten'), 'margin: 10px;', 'Ignore terminating `;` in snippet');
// https://github.com/microsoft/vscode/issues/59951
equal(expand('fz'), 'font-size: ${0};');
equal(expand('fz12'), 'font-size: 12px;');
equal(expand('fsz'), 'font-size: ${0};');
equal(expand('fsz12'), 'font-size: 12px;');
equal(expand('fs'), 'font-style: ${1:italic};');
// https://github.com/emmetio/emmet/issues/558
equal(expand('us'), 'user-select: none;');
// https://github.com/microsoft/vscode/issues/105697
equal(expand('opa1'), 'opacity: 1;', 'Unitless property');
equal(expand('opa.1'), 'opacity: 0.1;', 'Unitless property');
equal(expand('opa.a'), 'opacity: .a;', 'Unitless property');
});
it('numeric with format options', () => {
const config = resolveConfig({
type: 'stylesheet',
options: {
'stylesheet.intUnit': 'pt',
'stylesheet.floatUnit': 'vh',
'stylesheet.unitAliases': {
e: 'em',
p: '%',
x: 'ex',
r: ' / @rem'
}
}
});
equal(expand('p0', config), 'padding: 0;', 'No unit for 0');
equal(expand('p10', config), 'padding: 10pt;', '`pt` unit for integers');
equal(expand('p.4', config), 'padding: 0.4vh;', '`vh` for floats');
equal(expand('p10p', config), 'padding: 10%;', 'unit alias');
equal(expand('z10', config), 'z-index: 10;', 'Unitless property');
equal(expand('p10r', config), 'padding: 10 / @rem;', 'unit alias');
});
it('important', () => {
equal(expand('!'), '!important');
equal(expand('p!'), 'padding: ${0} !important;');
equal(expand('p0!'), 'padding: 0 !important;');
});
it('color', () => {
equal(expand('c'), 'color: ${1:#000};');
equal(expand('c#'), 'color: #000;');
equal(expand('c#f.5'), 'color: rgba(255, 255, 255, 0.5);');
equal(expand('c#f.5!'), 'color: rgba(255, 255, 255, 0.5) !important;');
equal(expand('bgc'), 'background-color: #${1:fff};');
});
it('snippets', () => {
equal(expand('@'), '@media ${1:screen} {\n\t${0}\n}');
// Insert value into snippet fields
equal(expand('@k-name'), '@keyframes name {\n\t${2}\n}');
equal(expand('@k-name10'), '@keyframes name {\n\t10\n}');
equal(expand('gt'), 'grid-template: repeat(2, auto) / repeat(auto-fit, minmax(250px, 1fr));');
});
it('multiple properties', () => {
equal(expand('p10+m10-20'), 'padding: 10px;\nmargin: 10px 20px;');
equal(expand('p+bd'), 'padding: ${0};\nborder: ${1:1px} ${2:solid} ${3:#000};');
});
it('functions', () => {
equal(expand('trf-s(2)'), 'transform: scale(2, ${2:y});');
equal(expand('trf-s(2, 3)'), 'transform: scale(2, 3);');
});
it('case insensitive matches', () => {
equal(expand('trf:rx'), 'transform: rotateX(${1:angle});');
});
it('gradient resolver', () => {
equal(expand('lg'), 'background-image: linear-gradient(${0});');
equal(expand('lg(to right, #0, #f00.5)'), 'background-image: linear-gradient(to right, #000, rgba(255, 0, 0, 0.5));');
});
it('unmatched abbreviation', () => {
// This example is useless: it’s unexpected to receive `align-self: unset`
// for `auto` snippet
// equal(expand('auto', resolveConfig({
// type: 'stylesheet',
// options: { 'stylesheet.fuzzySearchMinScore': 0 }
// })), 'align-self: unset;');
equal(expand('auto'), 'auto: ${0};');
});
it('CSS-in-JS', () => {
const config = resolveConfig({
type: 'stylesheet',
options: {
'stylesheet.json': true,
'stylesheet.between': ': '
}
});
equal(expand('p10+mt10-20', config), 'padding: 10,\nmarginTop: \'10px 20px\',');
equal(expand('bgc', config), 'backgroundColor: \'#fff\',');
});
it('resolve context value', () => {
const config = resolveConfig({
type: 'stylesheet',
context: { name: 'align-content' }
});
equal(expand('s', config), 'start');
equal(expand('a', config), 'auto');
});
it('limit snippets by scope', () => {
const sectionScope = resolveConfig({
type: 'stylesheet',
context: { name: CSSAbbreviationScope.Section },
snippets: {
mten: 'margin: 10px;',
fsz: 'font-size',
myCenterAwesome: 'body {\n\tdisplay: grid;\n}'
}
});
const propertyScope = resolveConfig({
type: 'stylesheet',
context: { name: CSSAbbreviationScope.Property },
snippets: {
mten: 'margin: 10px;',
fsz: 'font-size',
myCenterAwesome: 'body {\n\tdisplay: grid;\n}'
}
});
equal(expand('m', sectionScope), 'body {\n\tdisplay: grid;\n}');
equal(expand('b', sectionScope), '');
equal(expand('m', propertyScope), 'margin: ;');
});
});
<MSG> Added scoring tests
<DFF> @@ -1,5 +1,6 @@
-import { strictEqual as equal } from 'assert';
+import { strictEqual as equal, ok } from 'assert';
import { stylesheet as expandAbbreviation, parseStylesheetSnippets, resolveConfig } from '../src';
+import score from '../src/stylesheet/score';
const defaultConfig = resolveConfig({
type: 'stylesheet',
@@ -17,6 +18,36 @@ function expand(abbr: string, config = defaultConfig) {
}
describe('Stylesheet abbreviations', () => {
+ describe('Scoring', () => {
+ const pick = (abbr: string, items: string[]) => items
+ .map(item => ({ item, score: score(abbr, item) }))
+ .filter(obj => obj.score)
+ .sort((a, b) => b.score - a.score)
+ .map(obj => obj.item)[0];
+
+ it('compare scores', () => {
+ equal(score('aaa', 'aaa'), 1);
+ equal(score('baa', 'aaa'), 0);
+
+ ok(!score('b', 'aaa'));
+ ok(score('a', 'aaa'));
+ ok(score('a', 'abc'));
+ ok(score('ac', 'abc'));
+ ok(score('a', 'aaa') < score('aa', 'aaa'));
+ ok(score('ab', 'abc') > score('ab', 'acb'));
+
+ // acronym bonus
+ ok(score('ab', 'a-b') > score('ab', 'acb'));
+ });
+
+ it('pick padding or position', () => {
+ const items = ['p', 'pb', 'pl', 'pos', 'pa', 'oa', 'soa', 'pr', 'pt'];
+
+ equal(pick('p', items), 'p');
+ equal(pick('poa', items), 'pos');
+ });
+ });
+
it('keywords', () => {
equal(expand('bd1-s'), 'border: 1px solid;');
equal(expand('dib'), 'display: inline-block;');
| 32 | Added scoring tests | 1 | .ts | ts | mit | emmetio/emmet |
10071909 | <NME> split.gemspec
<BEF> # -*- encoding: utf-8 -*-
# frozen_string_literal: true
$:.push File.expand_path("../lib", __FILE__)
require "split/version"
Gem::Specification.new do |s|
s.name = "split"
s.version = Split::VERSION
s.platform = Gem::Platform::RUBY
s.authors = ["Andrew Nesbitt"]
s.licenses = ["MIT"]
s.email = ["[email protected]"]
s.homepage = "https://github.com/splitrb/split"
s.summary = "Rack based split testing framework"
s.metadata = {
"homepage_uri" => "https://github.com/splitrb/split",
"changelog_uri" => "https://github.com/splitrb/split/blob/main/CHANGELOG.md",
"source_code_uri" => "https://github.com/splitrb/split",
"bug_tracker_uri" => "https://github.com/splitrb/split/issues",
"wiki_uri" => "https://github.com/splitrb/split/wiki",
"mailing_list_uri" => "https://groups.google.com/d/forum/split-ruby"
}
s.required_ruby_version = ">= 2.5.0"
s.required_rubygems_version = ">= 2.0.0"
s.test_files = `git ls-files -- {test,spec,features}/*`.split("\n")
s.require_paths = ["lib"]
s.add_dependency 'redis', '>= 2.1'
s.add_dependency 'sinatra', '>= 1.2.6'
s.add_dependency 'rubystats', '>= 0.3.0'
s.add_development_dependency "bundler", ">= 1.17"
s.add_development_dependency "simplecov", "~> 0.15"
s.add_development_dependency "rack-test", "~> 2.0"
s.add_development_dependency "rake", "~> 13"
s.add_development_dependency "rspec", "~> 3.7"
s.add_development_dependency "pry", "~> 0.10"
s.add_development_dependency "rails", ">= 5.0"
end
<MSG> Bump minimum required redis version
<DFF> @@ -29,7 +29,7 @@ Gem::Specification.new do |s|
s.test_files = `git ls-files -- {test,spec,features}/*`.split("\n")
s.require_paths = ["lib"]
- s.add_dependency 'redis', '>= 2.1'
+ s.add_dependency 'redis', '>= 4.2'
s.add_dependency 'sinatra', '>= 1.2.6'
s.add_dependency 'rubystats', '>= 0.3.0'
| 1 | Bump minimum required redis version | 1 | .gemspec | gemspec | mit | splitrb/split |
10071910 | <NME> split.gemspec
<BEF> # -*- encoding: utf-8 -*-
# frozen_string_literal: true
$:.push File.expand_path("../lib", __FILE__)
require "split/version"
Gem::Specification.new do |s|
s.name = "split"
s.version = Split::VERSION
s.platform = Gem::Platform::RUBY
s.authors = ["Andrew Nesbitt"]
s.licenses = ["MIT"]
s.email = ["[email protected]"]
s.homepage = "https://github.com/splitrb/split"
s.summary = "Rack based split testing framework"
s.metadata = {
"homepage_uri" => "https://github.com/splitrb/split",
"changelog_uri" => "https://github.com/splitrb/split/blob/main/CHANGELOG.md",
"source_code_uri" => "https://github.com/splitrb/split",
"bug_tracker_uri" => "https://github.com/splitrb/split/issues",
"wiki_uri" => "https://github.com/splitrb/split/wiki",
"mailing_list_uri" => "https://groups.google.com/d/forum/split-ruby"
}
s.required_ruby_version = ">= 2.5.0"
s.required_rubygems_version = ">= 2.0.0"
s.test_files = `git ls-files -- {test,spec,features}/*`.split("\n")
s.require_paths = ["lib"]
s.add_dependency 'redis', '>= 2.1'
s.add_dependency 'sinatra', '>= 1.2.6'
s.add_dependency 'rubystats', '>= 0.3.0'
s.add_development_dependency "bundler", ">= 1.17"
s.add_development_dependency "simplecov", "~> 0.15"
s.add_development_dependency "rack-test", "~> 2.0"
s.add_development_dependency "rake", "~> 13"
s.add_development_dependency "rspec", "~> 3.7"
s.add_development_dependency "pry", "~> 0.10"
s.add_development_dependency "rails", ">= 5.0"
end
<MSG> Bump minimum required redis version
<DFF> @@ -29,7 +29,7 @@ Gem::Specification.new do |s|
s.test_files = `git ls-files -- {test,spec,features}/*`.split("\n")
s.require_paths = ["lib"]
- s.add_dependency 'redis', '>= 2.1'
+ s.add_dependency 'redis', '>= 4.2'
s.add_dependency 'sinatra', '>= 1.2.6'
s.add_dependency 'rubystats', '>= 0.3.0'
| 1 | Bump minimum required redis version | 1 | .gemspec | gemspec | mit | splitrb/split |
10071911 | <NME> split.gemspec
<BEF> # -*- encoding: utf-8 -*-
# frozen_string_literal: true
$:.push File.expand_path("../lib", __FILE__)
require "split/version"
Gem::Specification.new do |s|
s.name = "split"
s.version = Split::VERSION
s.platform = Gem::Platform::RUBY
s.authors = ["Andrew Nesbitt"]
s.licenses = ["MIT"]
s.email = ["[email protected]"]
s.homepage = "https://github.com/splitrb/split"
s.summary = "Rack based split testing framework"
s.metadata = {
"homepage_uri" => "https://github.com/splitrb/split",
"changelog_uri" => "https://github.com/splitrb/split/blob/main/CHANGELOG.md",
"source_code_uri" => "https://github.com/splitrb/split",
"bug_tracker_uri" => "https://github.com/splitrb/split/issues",
"wiki_uri" => "https://github.com/splitrb/split/wiki",
"mailing_list_uri" => "https://groups.google.com/d/forum/split-ruby"
}
s.required_ruby_version = ">= 2.5.0"
s.required_rubygems_version = ">= 2.0.0"
s.test_files = `git ls-files -- {test,spec,features}/*`.split("\n")
s.require_paths = ["lib"]
s.add_dependency 'redis', '>= 2.1'
s.add_dependency 'sinatra', '>= 1.2.6'
s.add_dependency 'rubystats', '>= 0.3.0'
s.add_development_dependency "bundler", ">= 1.17"
s.add_development_dependency "simplecov", "~> 0.15"
s.add_development_dependency "rack-test", "~> 2.0"
s.add_development_dependency "rake", "~> 13"
s.add_development_dependency "rspec", "~> 3.7"
s.add_development_dependency "pry", "~> 0.10"
s.add_development_dependency "rails", ">= 5.0"
end
<MSG> Bump minimum required redis version
<DFF> @@ -29,7 +29,7 @@ Gem::Specification.new do |s|
s.test_files = `git ls-files -- {test,spec,features}/*`.split("\n")
s.require_paths = ["lib"]
- s.add_dependency 'redis', '>= 2.1'
+ s.add_dependency 'redis', '>= 4.2'
s.add_dependency 'sinatra', '>= 1.2.6'
s.add_dependency 'rubystats', '>= 0.3.0'
| 1 | Bump minimum required redis version | 1 | .gemspec | gemspec | mit | splitrb/split |
10071912 | <NME> experiment_spec.rb
<BEF> # frozen_string_literal: true
require "spec_helper"
require "time"
describe Split::Experiment do
def new_experiment(goals = [])
Split::Experiment.new("link_color", alternatives: ["blue", "red", "green"], goals: goals)
end
def alternative(color)
Split::Alternative.new(color, "link_color")
end
let(:experiment) { new_experiment }
let(:blue) { alternative("blue") }
let(:green) { alternative("green") }
context "with an experiment" do
let(:experiment) { Split::Experiment.new("basket_text", alternatives: ["Basket", "Cart"]) }
it "should have a name" do
expect(experiment.name).to eq("basket_text")
end
it "should have alternatives" do
expect(experiment.alternatives.length).to be 2
end
it "should have alternatives with correct names" do
expect(experiment.alternatives.collect { |a| a.name }).to eq(["Basket", "Cart"])
end
it "should be resettable by default" do
expect(experiment.resettable).to be_truthy
end
it "should save to redis" do
experiment.save
expect(Split.redis.exists?("basket_text")).to be true
end
it "should save the start time to redis" do
experiment_start_time = Time.at(1372167761)
expect(Time).to receive(:now).and_return(experiment_start_time)
experiment.save
expect(Split::ExperimentCatalog.find("basket_text").start_time).to eq(experiment_start_time)
end
it "should not save the start time to redis when start_manually is enabled" do
expect(Split.configuration).to receive(:start_manually).and_return(true)
experiment.save
expect(Split::ExperimentCatalog.find("basket_text").start_time).to be_nil
end
it "should save the selected algorithm to redis" do
experiment_algorithm = Split::Algorithms::Whiplash
experiment.algorithm = experiment_algorithm
experiment.save
expect(Split::ExperimentCatalog.find("basket_text").algorithm).to eq(experiment_algorithm)
end
it "should handle having a start time stored as a string" do
experiment_start_time = Time.parse("Sat Mar 03 14:01:03")
expect(Time).to receive(:now).twice.and_return(experiment_start_time)
experiment.save
Split.redis.hset(:experiment_start_times, experiment.name, experiment_start_time.to_s)
expect(Split::ExperimentCatalog.find("basket_text").start_time).to eq(experiment_start_time)
end
it "should handle not having a start time" do
experiment_start_time = Time.parse("Sat Mar 03 14:01:03")
expect(Time).to receive(:now).and_return(experiment_start_time)
experiment.save
Split.redis.hdel(:experiment_start_times, experiment.name)
expect(Split::ExperimentCatalog.find("basket_text").start_time).to be_nil
end
it "should not create duplicates when saving multiple times" do
experiment.save
experiment.save
expect(Split.redis.exists?("basket_text")).to be true
expect(Split.redis.lrange("basket_text", 0, -1)).to eq(['{"Basket":1}', '{"Cart":1}'])
end
describe "new record?" do
it "should know if it hasn't been saved yet" do
expect(experiment.new_record?).to be_truthy
end
it "should know if it has been saved yet" do
experiment.save
expect(experiment.new_record?).to be_falsey
end
end
describe "control" do
it "should be the first alternative" do
experiment.save
expect(experiment.control.name).to eq("Basket")
end
end
end
describe "initialization" do
it "should set the algorithm when passed as an option to the initializer" do
experiment = Split::Experiment.new("basket_text", alternatives: ["Basket", "Cart"], algorithm: Split::Algorithms::Whiplash)
expect(experiment.algorithm).to eq(Split::Algorithms::Whiplash)
end
it "should be possible to make an experiment not resettable" do
experiment = Split::Experiment.new("basket_text", alternatives: ["Basket", "Cart"], resettable: false)
expect(experiment.resettable).to be_falsey
end
context "from configuration" do
let(:experiment_name) { :my_experiment }
let(:experiments) do
{
experiment_name => {
alternatives: ["Control Opt", "Alt one"]
}
}
end
before { Split.configuration.experiments = experiments }
it "assigns default values to the experiment" do
expect(Split::Experiment.new(experiment_name).resettable).to eq(true)
end
end
end
describe "persistent configuration" do
it "should persist resettable in redis" do
experiment = Split::Experiment.new("basket_text", alternatives: ["Basket", "Cart"], resettable: false)
experiment.save
e = Split::ExperimentCatalog.find("basket_text")
expect(e).to eq(experiment)
expect(e.resettable).to be_falsey
end
describe '#metadata' do
let(:experiment) { Split::Experiment.new('basket_text', :alternatives => ['Basket', "Cart"], :algorithm => Split::Algorithms::Whiplash, :metadata => meta) }
context 'simple hash' do
let(:meta) { { 'basket' => 'a', 'cart' => 'b' } }
it "should persist metadata in redis" do
experiment.save
e = Split::ExperimentCatalog.find('basket_text')
expect(e).to eq(experiment)
expect(e.metadata).to eq(meta)
end
context "nested hash" do
context 'nested hash' do
let(:meta) { { 'basket' => { 'one' => 'two' }, 'cart' => 'b' } }
it "should persist metadata in redis" do
experiment.save
e = Split::ExperimentCatalog.find('basket_text')
expect(e).to eq(experiment)
expect(e.metadata).to eq(meta)
end
end
it "should persist algorithm in redis" do
experiment = Split::Experiment.new("basket_text", alternatives: ["Basket", "Cart"], algorithm: Split::Algorithms::Whiplash)
experiment.save
e = Split::ExperimentCatalog.find("basket_text")
expect(e).to eq(experiment)
expect(e.algorithm).to eq(Split::Algorithms::Whiplash)
end
it "should persist a new experiment in redis, that does not exist in the configuration file" do
experiment = Split::Experiment.new("foobar", alternatives: ["tra", "la"], algorithm: Split::Algorithms::Whiplash)
experiment.save
e = Split::ExperimentCatalog.find("foobar")
expect(e).to eq(experiment)
expect(e.alternatives.collect { |a| a.name }).to eq(["tra", "la"])
end
end
describe "deleting" do
it "should delete itself" do
experiment = Split::Experiment.new("basket_text", alternatives: [ "Basket", "Cart"])
experiment.save
experiment.delete
expect(Split.redis.exists?("link_color")).to be false
expect(Split::ExperimentCatalog.find("link_color")).to be_nil
end
it "should increment the version" do
expect(experiment.version).to eq(0)
experiment.delete
expect(experiment.version).to eq(1)
end
it "should call the on_experiment_delete hook" do
expect(Split.configuration.on_experiment_delete).to receive(:call)
experiment.delete
end
it "should call the on_before_experiment_delete hook" do
expect(Split.configuration.on_before_experiment_delete).to receive(:call)
experiment.delete
end
it "should reset the start time if the experiment should be manually started" do
Split.configuration.start_manually = true
experiment.start
experiment.delete
expect(experiment.start_time).to be_nil
end
it "should default cohorting back to false" do
experiment.disable_cohorting
expect(experiment.cohorting_disabled?).to eq(true)
experiment.delete
expect(experiment.cohorting_disabled?).to eq(false)
end
end
describe "winner" do
it "should have no winner initially" do
expect(experiment.winner).to be_nil
end
end
describe "winner=" do
it "should allow you to specify a winner" do
experiment.save
experiment.winner = "red"
expect(experiment.winner.name).to eq("red")
end
it "should call the on_experiment_winner_choose hook" do
expect(Split.configuration.on_experiment_winner_choose).to receive(:call)
experiment.winner = "green"
end
context "when has_winner state is memoized" do
before { expect(experiment).to_not have_winner }
it "should keep has_winner state consistent" do
experiment.winner = "red"
expect(experiment).to have_winner
end
end
end
describe "reset_winner" do
before { experiment.winner = "green" }
it "should reset the winner" do
experiment.reset_winner
expect(experiment.winner).to be_nil
end
context "when has_winner state is memoized" do
before { expect(experiment).to have_winner }
it "should keep has_winner state consistent" do
experiment.reset_winner
expect(experiment).to_not have_winner
end
end
end
describe "has_winner?" do
context "with winner" do
before { experiment.winner = "red" }
it "returns true" do
expect(experiment).to have_winner
end
end
context "without winner" do
it "returns false" do
expect(experiment).to_not have_winner
end
end
it "memoizes has_winner state" do
expect(experiment).to receive(:winner).once
expect(experiment).to_not have_winner
expect(experiment).to_not have_winner
end
end
describe "reset" do
let(:reset_manually) { false }
before do
allow(Split.configuration).to receive(:reset_manually).and_return(reset_manually)
experiment.save
green.increment_participation
green.increment_participation
end
it "should reset all alternatives" do
experiment.winner = "green"
expect(experiment.next_alternative.name).to eq("green")
green.increment_participation
experiment.reset
expect(green.participant_count).to eq(0)
expect(green.completed_count).to eq(0)
end
it "should reset the winner" do
experiment.winner = "green"
expect(experiment.next_alternative.name).to eq("green")
green.increment_participation
experiment.reset
expect(experiment.winner).to be_nil
end
it "should increment the version" do
expect(experiment.version).to eq(0)
experiment.reset
expect(experiment.version).to eq(1)
end
it "should call the on_experiment_reset hook" do
expect(Split.configuration.on_experiment_reset).to receive(:call)
experiment.reset
end
it "should call the on_before_experiment_reset hook" do
expect(Split.configuration.on_before_experiment_reset).to receive(:call)
experiment.reset
end
end
describe "algorithm" do
let(:experiment) { Split::ExperimentCatalog.find_or_create("link_color", "blue", "red", "green") }
it "should use the default algorithm if none is specified" do
expect(experiment.algorithm).to eq(Split.configuration.algorithm)
end
it "should use the user specified algorithm for this experiment if specified" do
experiment.algorithm = Split::Algorithms::Whiplash
expect(experiment.algorithm).to eq(Split::Algorithms::Whiplash)
end
end
describe "#next_alternative" do
context "with multiple alternatives" do
let(:experiment) { Split::ExperimentCatalog.find_or_create("link_color", "blue", "red", "green") }
context "with winner" do
it "should always return the winner" do
green = Split::Alternative.new("green", "link_color")
experiment.winner = "green"
expect(experiment.next_alternative.name).to eq("green")
green.increment_participation
expect(experiment.next_alternative.name).to eq("green")
end
end
context "without winner" do
it "should use the specified algorithm" do
experiment.algorithm = Split::Algorithms::Whiplash
expect(experiment.algorithm).to receive(:choose_alternative).and_return(Split::Alternative.new("green", "link_color"))
expect(experiment.next_alternative.name).to eq("green")
end
end
end
context "with single alternative" do
let(:experiment) { Split::ExperimentCatalog.find_or_create("link_color", "blue") }
it "should always return the only alternative" do
expect(experiment.next_alternative.name).to eq("blue")
expect(experiment.next_alternative.name).to eq("blue")
end
end
end
describe "#cohorting_disabled?" do
it "returns false when nothing has been configured" do
expect(experiment.cohorting_disabled?).to eq false
end
it "returns true when enable_cohorting is performed" do
experiment.enable_cohorting
expect(experiment.cohorting_disabled?).to eq false
end
it "returns false when nothing has been configured" do
experiment.disable_cohorting
expect(experiment.cohorting_disabled?).to eq true
end
end
describe "changing an existing experiment" do
def same_but_different_alternative
Split::ExperimentCatalog.find_or_create("link_color", "blue", "yellow", "orange")
end
it "should reset an experiment if it is loaded with different alternatives" do
experiment.save
blue.participant_count = 5
same_experiment = same_but_different_alternative
expect(same_experiment.alternatives.map(&:name)).to eq(["blue", "yellow", "orange"])
expect(blue.participant_count).to eq(0)
end
it "should only reset once" do
experiment.save
expect(experiment.version).to eq(0)
same_experiment = same_but_different_alternative
expect(same_experiment.version).to eq(1)
same_experiment_again = same_but_different_alternative
expect(same_experiment_again.version).to eq(1)
expect(same_experiment_again.version).to eq(1)
end
context 'when experiment configuration is changed' do
let(:reset_manually) { false }
experiment.save
allow(Split.configuration).to receive(:reset_manually).and_return(reset_manually)
green.increment_participation
green.increment_participation
experiment.set_alternatives_and_options(alternatives: %w(blue red green zip),
goals: %w(purchase))
experiment.save
end
it "resets all alternatives" do
expect(green.participant_count).to eq(0)
expect(green.completed_count).to eq(0)
end
context "when reset_manually is set" do
let(:reset_manually) { true }
it "does not reset alternatives" do
expect(green.participant_count).to eq(2)
expect(green.completed_count).to eq(0)
end
end
end
end
describe "alternatives passed as non-strings" do
it "should throw an exception if an alternative is passed that is not a string" do
expect { Split::ExperimentCatalog.find_or_create("link_color", :blue, :red) }.to raise_error(ArgumentError)
expect { Split::ExperimentCatalog.find_or_create("link_enabled", true, false) }.to raise_error(ArgumentError)
end
end
describe "specifying weights" do
let(:experiment_with_weight) {
Split::ExperimentCatalog.find_or_create("link_color", { "blue" => 1 }, { "red" => 2 })
}
it "should work for a new experiment" do
expect(experiment_with_weight.alternatives.map(&:weight)).to eq([1, 2])
end
it "should work for an existing experiment" do
experiment.save
expect(experiment_with_weight.alternatives.map(&:weight)).to eq([1, 2])
end
end
describe "specifying goals" do
let(:experiment) {
new_experiment(["purchase"])
}
context "saving experiment" do
let(:same_but_different_goals) { Split::ExperimentCatalog.find_or_create({ "link_color" => ["purchase", "refund"] }, "blue", "red", "green") }
before { experiment.save }
it "can find existing experiment" do
expect(Split::ExperimentCatalog.find("link_color").name).to eq("link_color")
end
it "should reset an experiment if it is loaded with different goals" do
same_but_different_goals
expect(Split::ExperimentCatalog.find("link_color").goals).to eq(["purchase", "refund"])
end
end
it "should have goals" do
expect(experiment.goals).to eq(["purchase"])
end
context "find or create experiment" do
it "should have correct goals" do
experiment = Split::ExperimentCatalog.find_or_create({ "link_color3" => ["purchase", "refund"] }, "blue", "red", "green")
expect(experiment.goals).to eq(["purchase", "refund"])
experiment = Split::ExperimentCatalog.find_or_create("link_color3", "blue", "red", "green")
expect(experiment.goals).to eq([])
end
end
end
describe "beta probability calculation" do
it "should return a hash with the probability of each alternative being the best" do
experiment = Split::ExperimentCatalog.find_or_create("mathematicians", "bernoulli", "poisson", "lagrange")
experiment.calc_winning_alternatives
expect(experiment.alternative_probabilities).not_to be_nil
end
it "should return between 46% and 54% probability for an experiment with 2 alternatives and no data" do
experiment = Split::ExperimentCatalog.find_or_create("scientists", "einstein", "bohr")
experiment.calc_winning_alternatives
expect(experiment.alternatives[0].p_winner).to be_within(0.04).of(0.50)
end
it "should calculate the probability of being the winning alternative separately for each goal", skip: true do
experiment = Split::ExperimentCatalog.find_or_create({ "link_color3" => ["purchase", "refund"] }, "blue", "red", "green")
goal1 = experiment.goals[0]
goal2 = experiment.goals[1]
experiment.alternatives.each do |alternative|
alternative.participant_count = 50
alternative.set_completed_count(10, goal1)
alternative.set_completed_count(15+rand(30), goal2)
end
experiment.calc_winning_alternatives
alt = experiment.alternatives[0]
p_goal1 = alt.p_winner(goal1)
p_goal2 = alt.p_winner(goal2)
expect(p_goal1).not_to be_within(0.04).of(p_goal2)
end
it "should return nil and not re-calculate probabilities if they have already been calculated today" do
experiment = Split::ExperimentCatalog.find_or_create({ "link_color3" => ["purchase", "refund"] }, "blue", "red", "green")
expect(experiment.calc_winning_alternatives).not_to be nil
expect(experiment.calc_winning_alternatives).to be nil
end
end
end
<MSG> Merge pull request #633 from splitrb/fix-metadata-updates
Removes metadata key when it updated to nil
<DFF> @@ -151,10 +151,23 @@ describe Split::Experiment do
describe '#metadata' do
let(:experiment) { Split::Experiment.new('basket_text', :alternatives => ['Basket', "Cart"], :algorithm => Split::Algorithms::Whiplash, :metadata => meta) }
+ let(:meta) { { a: 'b' }}
+
+ before do
+ experiment.save
+ end
+
+ it "should delete the key when metadata is removed" do
+ experiment.metadata = nil
+ experiment.save
+
+ expect(Split.redis.exists?(experiment.metadata_key)).to be_falsey
+ end
+
context 'simple hash' do
let(:meta) { { 'basket' => 'a', 'cart' => 'b' } }
+
it "should persist metadata in redis" do
- experiment.save
e = Split::ExperimentCatalog.find('basket_text')
expect(e).to eq(experiment)
expect(e.metadata).to eq(meta)
@@ -164,7 +177,6 @@ describe Split::Experiment do
context 'nested hash' do
let(:meta) { { 'basket' => { 'one' => 'two' }, 'cart' => 'b' } }
it "should persist metadata in redis" do
- experiment.save
e = Split::ExperimentCatalog.find('basket_text')
expect(e).to eq(experiment)
expect(e.metadata).to eq(meta)
@@ -436,6 +448,21 @@ describe Split::Experiment do
expect(same_experiment_again.version).to eq(1)
end
+ context "when metadata is changed" do
+ it "should increase version" do
+ experiment.save
+ experiment.metadata = { 'foo' => 'bar' }
+
+ expect { experiment.save }.to change { experiment.version }.by(1)
+ end
+
+ it "does not increase version" do
+ experiment.metadata = nil
+ experiment.save
+ expect { experiment.save }.to change { experiment.version }.by(0)
+ end
+ end
+
context 'when experiment configuration is changed' do
let(:reset_manually) { false }
| 29 | Merge pull request #633 from splitrb/fix-metadata-updates | 2 | .rb | rb | mit | splitrb/split |
10071913 | <NME> experiment_spec.rb
<BEF> # frozen_string_literal: true
require "spec_helper"
require "time"
describe Split::Experiment do
def new_experiment(goals = [])
Split::Experiment.new("link_color", alternatives: ["blue", "red", "green"], goals: goals)
end
def alternative(color)
Split::Alternative.new(color, "link_color")
end
let(:experiment) { new_experiment }
let(:blue) { alternative("blue") }
let(:green) { alternative("green") }
context "with an experiment" do
let(:experiment) { Split::Experiment.new("basket_text", alternatives: ["Basket", "Cart"]) }
it "should have a name" do
expect(experiment.name).to eq("basket_text")
end
it "should have alternatives" do
expect(experiment.alternatives.length).to be 2
end
it "should have alternatives with correct names" do
expect(experiment.alternatives.collect { |a| a.name }).to eq(["Basket", "Cart"])
end
it "should be resettable by default" do
expect(experiment.resettable).to be_truthy
end
it "should save to redis" do
experiment.save
expect(Split.redis.exists?("basket_text")).to be true
end
it "should save the start time to redis" do
experiment_start_time = Time.at(1372167761)
expect(Time).to receive(:now).and_return(experiment_start_time)
experiment.save
expect(Split::ExperimentCatalog.find("basket_text").start_time).to eq(experiment_start_time)
end
it "should not save the start time to redis when start_manually is enabled" do
expect(Split.configuration).to receive(:start_manually).and_return(true)
experiment.save
expect(Split::ExperimentCatalog.find("basket_text").start_time).to be_nil
end
it "should save the selected algorithm to redis" do
experiment_algorithm = Split::Algorithms::Whiplash
experiment.algorithm = experiment_algorithm
experiment.save
expect(Split::ExperimentCatalog.find("basket_text").algorithm).to eq(experiment_algorithm)
end
it "should handle having a start time stored as a string" do
experiment_start_time = Time.parse("Sat Mar 03 14:01:03")
expect(Time).to receive(:now).twice.and_return(experiment_start_time)
experiment.save
Split.redis.hset(:experiment_start_times, experiment.name, experiment_start_time.to_s)
expect(Split::ExperimentCatalog.find("basket_text").start_time).to eq(experiment_start_time)
end
it "should handle not having a start time" do
experiment_start_time = Time.parse("Sat Mar 03 14:01:03")
expect(Time).to receive(:now).and_return(experiment_start_time)
experiment.save
Split.redis.hdel(:experiment_start_times, experiment.name)
expect(Split::ExperimentCatalog.find("basket_text").start_time).to be_nil
end
it "should not create duplicates when saving multiple times" do
experiment.save
experiment.save
expect(Split.redis.exists?("basket_text")).to be true
expect(Split.redis.lrange("basket_text", 0, -1)).to eq(['{"Basket":1}', '{"Cart":1}'])
end
describe "new record?" do
it "should know if it hasn't been saved yet" do
expect(experiment.new_record?).to be_truthy
end
it "should know if it has been saved yet" do
experiment.save
expect(experiment.new_record?).to be_falsey
end
end
describe "control" do
it "should be the first alternative" do
experiment.save
expect(experiment.control.name).to eq("Basket")
end
end
end
describe "initialization" do
it "should set the algorithm when passed as an option to the initializer" do
experiment = Split::Experiment.new("basket_text", alternatives: ["Basket", "Cart"], algorithm: Split::Algorithms::Whiplash)
expect(experiment.algorithm).to eq(Split::Algorithms::Whiplash)
end
it "should be possible to make an experiment not resettable" do
experiment = Split::Experiment.new("basket_text", alternatives: ["Basket", "Cart"], resettable: false)
expect(experiment.resettable).to be_falsey
end
context "from configuration" do
let(:experiment_name) { :my_experiment }
let(:experiments) do
{
experiment_name => {
alternatives: ["Control Opt", "Alt one"]
}
}
end
before { Split.configuration.experiments = experiments }
it "assigns default values to the experiment" do
expect(Split::Experiment.new(experiment_name).resettable).to eq(true)
end
end
end
describe "persistent configuration" do
it "should persist resettable in redis" do
experiment = Split::Experiment.new("basket_text", alternatives: ["Basket", "Cart"], resettable: false)
experiment.save
e = Split::ExperimentCatalog.find("basket_text")
expect(e).to eq(experiment)
expect(e.resettable).to be_falsey
end
describe '#metadata' do
let(:experiment) { Split::Experiment.new('basket_text', :alternatives => ['Basket', "Cart"], :algorithm => Split::Algorithms::Whiplash, :metadata => meta) }
context 'simple hash' do
let(:meta) { { 'basket' => 'a', 'cart' => 'b' } }
it "should persist metadata in redis" do
experiment.save
e = Split::ExperimentCatalog.find('basket_text')
expect(e).to eq(experiment)
expect(e.metadata).to eq(meta)
end
context "nested hash" do
context 'nested hash' do
let(:meta) { { 'basket' => { 'one' => 'two' }, 'cart' => 'b' } }
it "should persist metadata in redis" do
experiment.save
e = Split::ExperimentCatalog.find('basket_text')
expect(e).to eq(experiment)
expect(e.metadata).to eq(meta)
end
end
it "should persist algorithm in redis" do
experiment = Split::Experiment.new("basket_text", alternatives: ["Basket", "Cart"], algorithm: Split::Algorithms::Whiplash)
experiment.save
e = Split::ExperimentCatalog.find("basket_text")
expect(e).to eq(experiment)
expect(e.algorithm).to eq(Split::Algorithms::Whiplash)
end
it "should persist a new experiment in redis, that does not exist in the configuration file" do
experiment = Split::Experiment.new("foobar", alternatives: ["tra", "la"], algorithm: Split::Algorithms::Whiplash)
experiment.save
e = Split::ExperimentCatalog.find("foobar")
expect(e).to eq(experiment)
expect(e.alternatives.collect { |a| a.name }).to eq(["tra", "la"])
end
end
describe "deleting" do
it "should delete itself" do
experiment = Split::Experiment.new("basket_text", alternatives: [ "Basket", "Cart"])
experiment.save
experiment.delete
expect(Split.redis.exists?("link_color")).to be false
expect(Split::ExperimentCatalog.find("link_color")).to be_nil
end
it "should increment the version" do
expect(experiment.version).to eq(0)
experiment.delete
expect(experiment.version).to eq(1)
end
it "should call the on_experiment_delete hook" do
expect(Split.configuration.on_experiment_delete).to receive(:call)
experiment.delete
end
it "should call the on_before_experiment_delete hook" do
expect(Split.configuration.on_before_experiment_delete).to receive(:call)
experiment.delete
end
it "should reset the start time if the experiment should be manually started" do
Split.configuration.start_manually = true
experiment.start
experiment.delete
expect(experiment.start_time).to be_nil
end
it "should default cohorting back to false" do
experiment.disable_cohorting
expect(experiment.cohorting_disabled?).to eq(true)
experiment.delete
expect(experiment.cohorting_disabled?).to eq(false)
end
end
describe "winner" do
it "should have no winner initially" do
expect(experiment.winner).to be_nil
end
end
describe "winner=" do
it "should allow you to specify a winner" do
experiment.save
experiment.winner = "red"
expect(experiment.winner.name).to eq("red")
end
it "should call the on_experiment_winner_choose hook" do
expect(Split.configuration.on_experiment_winner_choose).to receive(:call)
experiment.winner = "green"
end
context "when has_winner state is memoized" do
before { expect(experiment).to_not have_winner }
it "should keep has_winner state consistent" do
experiment.winner = "red"
expect(experiment).to have_winner
end
end
end
describe "reset_winner" do
before { experiment.winner = "green" }
it "should reset the winner" do
experiment.reset_winner
expect(experiment.winner).to be_nil
end
context "when has_winner state is memoized" do
before { expect(experiment).to have_winner }
it "should keep has_winner state consistent" do
experiment.reset_winner
expect(experiment).to_not have_winner
end
end
end
describe "has_winner?" do
context "with winner" do
before { experiment.winner = "red" }
it "returns true" do
expect(experiment).to have_winner
end
end
context "without winner" do
it "returns false" do
expect(experiment).to_not have_winner
end
end
it "memoizes has_winner state" do
expect(experiment).to receive(:winner).once
expect(experiment).to_not have_winner
expect(experiment).to_not have_winner
end
end
describe "reset" do
let(:reset_manually) { false }
before do
allow(Split.configuration).to receive(:reset_manually).and_return(reset_manually)
experiment.save
green.increment_participation
green.increment_participation
end
it "should reset all alternatives" do
experiment.winner = "green"
expect(experiment.next_alternative.name).to eq("green")
green.increment_participation
experiment.reset
expect(green.participant_count).to eq(0)
expect(green.completed_count).to eq(0)
end
it "should reset the winner" do
experiment.winner = "green"
expect(experiment.next_alternative.name).to eq("green")
green.increment_participation
experiment.reset
expect(experiment.winner).to be_nil
end
it "should increment the version" do
expect(experiment.version).to eq(0)
experiment.reset
expect(experiment.version).to eq(1)
end
it "should call the on_experiment_reset hook" do
expect(Split.configuration.on_experiment_reset).to receive(:call)
experiment.reset
end
it "should call the on_before_experiment_reset hook" do
expect(Split.configuration.on_before_experiment_reset).to receive(:call)
experiment.reset
end
end
describe "algorithm" do
let(:experiment) { Split::ExperimentCatalog.find_or_create("link_color", "blue", "red", "green") }
it "should use the default algorithm if none is specified" do
expect(experiment.algorithm).to eq(Split.configuration.algorithm)
end
it "should use the user specified algorithm for this experiment if specified" do
experiment.algorithm = Split::Algorithms::Whiplash
expect(experiment.algorithm).to eq(Split::Algorithms::Whiplash)
end
end
describe "#next_alternative" do
context "with multiple alternatives" do
let(:experiment) { Split::ExperimentCatalog.find_or_create("link_color", "blue", "red", "green") }
context "with winner" do
it "should always return the winner" do
green = Split::Alternative.new("green", "link_color")
experiment.winner = "green"
expect(experiment.next_alternative.name).to eq("green")
green.increment_participation
expect(experiment.next_alternative.name).to eq("green")
end
end
context "without winner" do
it "should use the specified algorithm" do
experiment.algorithm = Split::Algorithms::Whiplash
expect(experiment.algorithm).to receive(:choose_alternative).and_return(Split::Alternative.new("green", "link_color"))
expect(experiment.next_alternative.name).to eq("green")
end
end
end
context "with single alternative" do
let(:experiment) { Split::ExperimentCatalog.find_or_create("link_color", "blue") }
it "should always return the only alternative" do
expect(experiment.next_alternative.name).to eq("blue")
expect(experiment.next_alternative.name).to eq("blue")
end
end
end
describe "#cohorting_disabled?" do
it "returns false when nothing has been configured" do
expect(experiment.cohorting_disabled?).to eq false
end
it "returns true when enable_cohorting is performed" do
experiment.enable_cohorting
expect(experiment.cohorting_disabled?).to eq false
end
it "returns false when nothing has been configured" do
experiment.disable_cohorting
expect(experiment.cohorting_disabled?).to eq true
end
end
describe "changing an existing experiment" do
def same_but_different_alternative
Split::ExperimentCatalog.find_or_create("link_color", "blue", "yellow", "orange")
end
it "should reset an experiment if it is loaded with different alternatives" do
experiment.save
blue.participant_count = 5
same_experiment = same_but_different_alternative
expect(same_experiment.alternatives.map(&:name)).to eq(["blue", "yellow", "orange"])
expect(blue.participant_count).to eq(0)
end
it "should only reset once" do
experiment.save
expect(experiment.version).to eq(0)
same_experiment = same_but_different_alternative
expect(same_experiment.version).to eq(1)
same_experiment_again = same_but_different_alternative
expect(same_experiment_again.version).to eq(1)
expect(same_experiment_again.version).to eq(1)
end
context 'when experiment configuration is changed' do
let(:reset_manually) { false }
experiment.save
allow(Split.configuration).to receive(:reset_manually).and_return(reset_manually)
green.increment_participation
green.increment_participation
experiment.set_alternatives_and_options(alternatives: %w(blue red green zip),
goals: %w(purchase))
experiment.save
end
it "resets all alternatives" do
expect(green.participant_count).to eq(0)
expect(green.completed_count).to eq(0)
end
context "when reset_manually is set" do
let(:reset_manually) { true }
it "does not reset alternatives" do
expect(green.participant_count).to eq(2)
expect(green.completed_count).to eq(0)
end
end
end
end
describe "alternatives passed as non-strings" do
it "should throw an exception if an alternative is passed that is not a string" do
expect { Split::ExperimentCatalog.find_or_create("link_color", :blue, :red) }.to raise_error(ArgumentError)
expect { Split::ExperimentCatalog.find_or_create("link_enabled", true, false) }.to raise_error(ArgumentError)
end
end
describe "specifying weights" do
let(:experiment_with_weight) {
Split::ExperimentCatalog.find_or_create("link_color", { "blue" => 1 }, { "red" => 2 })
}
it "should work for a new experiment" do
expect(experiment_with_weight.alternatives.map(&:weight)).to eq([1, 2])
end
it "should work for an existing experiment" do
experiment.save
expect(experiment_with_weight.alternatives.map(&:weight)).to eq([1, 2])
end
end
describe "specifying goals" do
let(:experiment) {
new_experiment(["purchase"])
}
context "saving experiment" do
let(:same_but_different_goals) { Split::ExperimentCatalog.find_or_create({ "link_color" => ["purchase", "refund"] }, "blue", "red", "green") }
before { experiment.save }
it "can find existing experiment" do
expect(Split::ExperimentCatalog.find("link_color").name).to eq("link_color")
end
it "should reset an experiment if it is loaded with different goals" do
same_but_different_goals
expect(Split::ExperimentCatalog.find("link_color").goals).to eq(["purchase", "refund"])
end
end
it "should have goals" do
expect(experiment.goals).to eq(["purchase"])
end
context "find or create experiment" do
it "should have correct goals" do
experiment = Split::ExperimentCatalog.find_or_create({ "link_color3" => ["purchase", "refund"] }, "blue", "red", "green")
expect(experiment.goals).to eq(["purchase", "refund"])
experiment = Split::ExperimentCatalog.find_or_create("link_color3", "blue", "red", "green")
expect(experiment.goals).to eq([])
end
end
end
describe "beta probability calculation" do
it "should return a hash with the probability of each alternative being the best" do
experiment = Split::ExperimentCatalog.find_or_create("mathematicians", "bernoulli", "poisson", "lagrange")
experiment.calc_winning_alternatives
expect(experiment.alternative_probabilities).not_to be_nil
end
it "should return between 46% and 54% probability for an experiment with 2 alternatives and no data" do
experiment = Split::ExperimentCatalog.find_or_create("scientists", "einstein", "bohr")
experiment.calc_winning_alternatives
expect(experiment.alternatives[0].p_winner).to be_within(0.04).of(0.50)
end
it "should calculate the probability of being the winning alternative separately for each goal", skip: true do
experiment = Split::ExperimentCatalog.find_or_create({ "link_color3" => ["purchase", "refund"] }, "blue", "red", "green")
goal1 = experiment.goals[0]
goal2 = experiment.goals[1]
experiment.alternatives.each do |alternative|
alternative.participant_count = 50
alternative.set_completed_count(10, goal1)
alternative.set_completed_count(15+rand(30), goal2)
end
experiment.calc_winning_alternatives
alt = experiment.alternatives[0]
p_goal1 = alt.p_winner(goal1)
p_goal2 = alt.p_winner(goal2)
expect(p_goal1).not_to be_within(0.04).of(p_goal2)
end
it "should return nil and not re-calculate probabilities if they have already been calculated today" do
experiment = Split::ExperimentCatalog.find_or_create({ "link_color3" => ["purchase", "refund"] }, "blue", "red", "green")
expect(experiment.calc_winning_alternatives).not_to be nil
expect(experiment.calc_winning_alternatives).to be nil
end
end
end
<MSG> Merge pull request #633 from splitrb/fix-metadata-updates
Removes metadata key when it updated to nil
<DFF> @@ -151,10 +151,23 @@ describe Split::Experiment do
describe '#metadata' do
let(:experiment) { Split::Experiment.new('basket_text', :alternatives => ['Basket', "Cart"], :algorithm => Split::Algorithms::Whiplash, :metadata => meta) }
+ let(:meta) { { a: 'b' }}
+
+ before do
+ experiment.save
+ end
+
+ it "should delete the key when metadata is removed" do
+ experiment.metadata = nil
+ experiment.save
+
+ expect(Split.redis.exists?(experiment.metadata_key)).to be_falsey
+ end
+
context 'simple hash' do
let(:meta) { { 'basket' => 'a', 'cart' => 'b' } }
+
it "should persist metadata in redis" do
- experiment.save
e = Split::ExperimentCatalog.find('basket_text')
expect(e).to eq(experiment)
expect(e.metadata).to eq(meta)
@@ -164,7 +177,6 @@ describe Split::Experiment do
context 'nested hash' do
let(:meta) { { 'basket' => { 'one' => 'two' }, 'cart' => 'b' } }
it "should persist metadata in redis" do
- experiment.save
e = Split::ExperimentCatalog.find('basket_text')
expect(e).to eq(experiment)
expect(e.metadata).to eq(meta)
@@ -436,6 +448,21 @@ describe Split::Experiment do
expect(same_experiment_again.version).to eq(1)
end
+ context "when metadata is changed" do
+ it "should increase version" do
+ experiment.save
+ experiment.metadata = { 'foo' => 'bar' }
+
+ expect { experiment.save }.to change { experiment.version }.by(1)
+ end
+
+ it "does not increase version" do
+ experiment.metadata = nil
+ experiment.save
+ expect { experiment.save }.to change { experiment.version }.by(0)
+ end
+ end
+
context 'when experiment configuration is changed' do
let(:reset_manually) { false }
| 29 | Merge pull request #633 from splitrb/fix-metadata-updates | 2 | .rb | rb | mit | splitrb/split |
10071914 | <NME> experiment_spec.rb
<BEF> # frozen_string_literal: true
require "spec_helper"
require "time"
describe Split::Experiment do
def new_experiment(goals = [])
Split::Experiment.new("link_color", alternatives: ["blue", "red", "green"], goals: goals)
end
def alternative(color)
Split::Alternative.new(color, "link_color")
end
let(:experiment) { new_experiment }
let(:blue) { alternative("blue") }
let(:green) { alternative("green") }
context "with an experiment" do
let(:experiment) { Split::Experiment.new("basket_text", alternatives: ["Basket", "Cart"]) }
it "should have a name" do
expect(experiment.name).to eq("basket_text")
end
it "should have alternatives" do
expect(experiment.alternatives.length).to be 2
end
it "should have alternatives with correct names" do
expect(experiment.alternatives.collect { |a| a.name }).to eq(["Basket", "Cart"])
end
it "should be resettable by default" do
expect(experiment.resettable).to be_truthy
end
it "should save to redis" do
experiment.save
expect(Split.redis.exists?("basket_text")).to be true
end
it "should save the start time to redis" do
experiment_start_time = Time.at(1372167761)
expect(Time).to receive(:now).and_return(experiment_start_time)
experiment.save
expect(Split::ExperimentCatalog.find("basket_text").start_time).to eq(experiment_start_time)
end
it "should not save the start time to redis when start_manually is enabled" do
expect(Split.configuration).to receive(:start_manually).and_return(true)
experiment.save
expect(Split::ExperimentCatalog.find("basket_text").start_time).to be_nil
end
it "should save the selected algorithm to redis" do
experiment_algorithm = Split::Algorithms::Whiplash
experiment.algorithm = experiment_algorithm
experiment.save
expect(Split::ExperimentCatalog.find("basket_text").algorithm).to eq(experiment_algorithm)
end
it "should handle having a start time stored as a string" do
experiment_start_time = Time.parse("Sat Mar 03 14:01:03")
expect(Time).to receive(:now).twice.and_return(experiment_start_time)
experiment.save
Split.redis.hset(:experiment_start_times, experiment.name, experiment_start_time.to_s)
expect(Split::ExperimentCatalog.find("basket_text").start_time).to eq(experiment_start_time)
end
it "should handle not having a start time" do
experiment_start_time = Time.parse("Sat Mar 03 14:01:03")
expect(Time).to receive(:now).and_return(experiment_start_time)
experiment.save
Split.redis.hdel(:experiment_start_times, experiment.name)
expect(Split::ExperimentCatalog.find("basket_text").start_time).to be_nil
end
it "should not create duplicates when saving multiple times" do
experiment.save
experiment.save
expect(Split.redis.exists?("basket_text")).to be true
expect(Split.redis.lrange("basket_text", 0, -1)).to eq(['{"Basket":1}', '{"Cart":1}'])
end
describe "new record?" do
it "should know if it hasn't been saved yet" do
expect(experiment.new_record?).to be_truthy
end
it "should know if it has been saved yet" do
experiment.save
expect(experiment.new_record?).to be_falsey
end
end
describe "control" do
it "should be the first alternative" do
experiment.save
expect(experiment.control.name).to eq("Basket")
end
end
end
describe "initialization" do
it "should set the algorithm when passed as an option to the initializer" do
experiment = Split::Experiment.new("basket_text", alternatives: ["Basket", "Cart"], algorithm: Split::Algorithms::Whiplash)
expect(experiment.algorithm).to eq(Split::Algorithms::Whiplash)
end
it "should be possible to make an experiment not resettable" do
experiment = Split::Experiment.new("basket_text", alternatives: ["Basket", "Cart"], resettable: false)
expect(experiment.resettable).to be_falsey
end
context "from configuration" do
let(:experiment_name) { :my_experiment }
let(:experiments) do
{
experiment_name => {
alternatives: ["Control Opt", "Alt one"]
}
}
end
before { Split.configuration.experiments = experiments }
it "assigns default values to the experiment" do
expect(Split::Experiment.new(experiment_name).resettable).to eq(true)
end
end
end
describe "persistent configuration" do
it "should persist resettable in redis" do
experiment = Split::Experiment.new("basket_text", alternatives: ["Basket", "Cart"], resettable: false)
experiment.save
e = Split::ExperimentCatalog.find("basket_text")
expect(e).to eq(experiment)
expect(e.resettable).to be_falsey
end
describe '#metadata' do
let(:experiment) { Split::Experiment.new('basket_text', :alternatives => ['Basket', "Cart"], :algorithm => Split::Algorithms::Whiplash, :metadata => meta) }
context 'simple hash' do
let(:meta) { { 'basket' => 'a', 'cart' => 'b' } }
it "should persist metadata in redis" do
experiment.save
e = Split::ExperimentCatalog.find('basket_text')
expect(e).to eq(experiment)
expect(e.metadata).to eq(meta)
end
context "nested hash" do
context 'nested hash' do
let(:meta) { { 'basket' => { 'one' => 'two' }, 'cart' => 'b' } }
it "should persist metadata in redis" do
experiment.save
e = Split::ExperimentCatalog.find('basket_text')
expect(e).to eq(experiment)
expect(e.metadata).to eq(meta)
end
end
it "should persist algorithm in redis" do
experiment = Split::Experiment.new("basket_text", alternatives: ["Basket", "Cart"], algorithm: Split::Algorithms::Whiplash)
experiment.save
e = Split::ExperimentCatalog.find("basket_text")
expect(e).to eq(experiment)
expect(e.algorithm).to eq(Split::Algorithms::Whiplash)
end
it "should persist a new experiment in redis, that does not exist in the configuration file" do
experiment = Split::Experiment.new("foobar", alternatives: ["tra", "la"], algorithm: Split::Algorithms::Whiplash)
experiment.save
e = Split::ExperimentCatalog.find("foobar")
expect(e).to eq(experiment)
expect(e.alternatives.collect { |a| a.name }).to eq(["tra", "la"])
end
end
describe "deleting" do
it "should delete itself" do
experiment = Split::Experiment.new("basket_text", alternatives: [ "Basket", "Cart"])
experiment.save
experiment.delete
expect(Split.redis.exists?("link_color")).to be false
expect(Split::ExperimentCatalog.find("link_color")).to be_nil
end
it "should increment the version" do
expect(experiment.version).to eq(0)
experiment.delete
expect(experiment.version).to eq(1)
end
it "should call the on_experiment_delete hook" do
expect(Split.configuration.on_experiment_delete).to receive(:call)
experiment.delete
end
it "should call the on_before_experiment_delete hook" do
expect(Split.configuration.on_before_experiment_delete).to receive(:call)
experiment.delete
end
it "should reset the start time if the experiment should be manually started" do
Split.configuration.start_manually = true
experiment.start
experiment.delete
expect(experiment.start_time).to be_nil
end
it "should default cohorting back to false" do
experiment.disable_cohorting
expect(experiment.cohorting_disabled?).to eq(true)
experiment.delete
expect(experiment.cohorting_disabled?).to eq(false)
end
end
describe "winner" do
it "should have no winner initially" do
expect(experiment.winner).to be_nil
end
end
describe "winner=" do
it "should allow you to specify a winner" do
experiment.save
experiment.winner = "red"
expect(experiment.winner.name).to eq("red")
end
it "should call the on_experiment_winner_choose hook" do
expect(Split.configuration.on_experiment_winner_choose).to receive(:call)
experiment.winner = "green"
end
context "when has_winner state is memoized" do
before { expect(experiment).to_not have_winner }
it "should keep has_winner state consistent" do
experiment.winner = "red"
expect(experiment).to have_winner
end
end
end
describe "reset_winner" do
before { experiment.winner = "green" }
it "should reset the winner" do
experiment.reset_winner
expect(experiment.winner).to be_nil
end
context "when has_winner state is memoized" do
before { expect(experiment).to have_winner }
it "should keep has_winner state consistent" do
experiment.reset_winner
expect(experiment).to_not have_winner
end
end
end
describe "has_winner?" do
context "with winner" do
before { experiment.winner = "red" }
it "returns true" do
expect(experiment).to have_winner
end
end
context "without winner" do
it "returns false" do
expect(experiment).to_not have_winner
end
end
it "memoizes has_winner state" do
expect(experiment).to receive(:winner).once
expect(experiment).to_not have_winner
expect(experiment).to_not have_winner
end
end
describe "reset" do
let(:reset_manually) { false }
before do
allow(Split.configuration).to receive(:reset_manually).and_return(reset_manually)
experiment.save
green.increment_participation
green.increment_participation
end
it "should reset all alternatives" do
experiment.winner = "green"
expect(experiment.next_alternative.name).to eq("green")
green.increment_participation
experiment.reset
expect(green.participant_count).to eq(0)
expect(green.completed_count).to eq(0)
end
it "should reset the winner" do
experiment.winner = "green"
expect(experiment.next_alternative.name).to eq("green")
green.increment_participation
experiment.reset
expect(experiment.winner).to be_nil
end
it "should increment the version" do
expect(experiment.version).to eq(0)
experiment.reset
expect(experiment.version).to eq(1)
end
it "should call the on_experiment_reset hook" do
expect(Split.configuration.on_experiment_reset).to receive(:call)
experiment.reset
end
it "should call the on_before_experiment_reset hook" do
expect(Split.configuration.on_before_experiment_reset).to receive(:call)
experiment.reset
end
end
describe "algorithm" do
let(:experiment) { Split::ExperimentCatalog.find_or_create("link_color", "blue", "red", "green") }
it "should use the default algorithm if none is specified" do
expect(experiment.algorithm).to eq(Split.configuration.algorithm)
end
it "should use the user specified algorithm for this experiment if specified" do
experiment.algorithm = Split::Algorithms::Whiplash
expect(experiment.algorithm).to eq(Split::Algorithms::Whiplash)
end
end
describe "#next_alternative" do
context "with multiple alternatives" do
let(:experiment) { Split::ExperimentCatalog.find_or_create("link_color", "blue", "red", "green") }
context "with winner" do
it "should always return the winner" do
green = Split::Alternative.new("green", "link_color")
experiment.winner = "green"
expect(experiment.next_alternative.name).to eq("green")
green.increment_participation
expect(experiment.next_alternative.name).to eq("green")
end
end
context "without winner" do
it "should use the specified algorithm" do
experiment.algorithm = Split::Algorithms::Whiplash
expect(experiment.algorithm).to receive(:choose_alternative).and_return(Split::Alternative.new("green", "link_color"))
expect(experiment.next_alternative.name).to eq("green")
end
end
end
context "with single alternative" do
let(:experiment) { Split::ExperimentCatalog.find_or_create("link_color", "blue") }
it "should always return the only alternative" do
expect(experiment.next_alternative.name).to eq("blue")
expect(experiment.next_alternative.name).to eq("blue")
end
end
end
describe "#cohorting_disabled?" do
it "returns false when nothing has been configured" do
expect(experiment.cohorting_disabled?).to eq false
end
it "returns true when enable_cohorting is performed" do
experiment.enable_cohorting
expect(experiment.cohorting_disabled?).to eq false
end
it "returns false when nothing has been configured" do
experiment.disable_cohorting
expect(experiment.cohorting_disabled?).to eq true
end
end
describe "changing an existing experiment" do
def same_but_different_alternative
Split::ExperimentCatalog.find_or_create("link_color", "blue", "yellow", "orange")
end
it "should reset an experiment if it is loaded with different alternatives" do
experiment.save
blue.participant_count = 5
same_experiment = same_but_different_alternative
expect(same_experiment.alternatives.map(&:name)).to eq(["blue", "yellow", "orange"])
expect(blue.participant_count).to eq(0)
end
it "should only reset once" do
experiment.save
expect(experiment.version).to eq(0)
same_experiment = same_but_different_alternative
expect(same_experiment.version).to eq(1)
same_experiment_again = same_but_different_alternative
expect(same_experiment_again.version).to eq(1)
expect(same_experiment_again.version).to eq(1)
end
context 'when experiment configuration is changed' do
let(:reset_manually) { false }
experiment.save
allow(Split.configuration).to receive(:reset_manually).and_return(reset_manually)
green.increment_participation
green.increment_participation
experiment.set_alternatives_and_options(alternatives: %w(blue red green zip),
goals: %w(purchase))
experiment.save
end
it "resets all alternatives" do
expect(green.participant_count).to eq(0)
expect(green.completed_count).to eq(0)
end
context "when reset_manually is set" do
let(:reset_manually) { true }
it "does not reset alternatives" do
expect(green.participant_count).to eq(2)
expect(green.completed_count).to eq(0)
end
end
end
end
describe "alternatives passed as non-strings" do
it "should throw an exception if an alternative is passed that is not a string" do
expect { Split::ExperimentCatalog.find_or_create("link_color", :blue, :red) }.to raise_error(ArgumentError)
expect { Split::ExperimentCatalog.find_or_create("link_enabled", true, false) }.to raise_error(ArgumentError)
end
end
describe "specifying weights" do
let(:experiment_with_weight) {
Split::ExperimentCatalog.find_or_create("link_color", { "blue" => 1 }, { "red" => 2 })
}
it "should work for a new experiment" do
expect(experiment_with_weight.alternatives.map(&:weight)).to eq([1, 2])
end
it "should work for an existing experiment" do
experiment.save
expect(experiment_with_weight.alternatives.map(&:weight)).to eq([1, 2])
end
end
describe "specifying goals" do
let(:experiment) {
new_experiment(["purchase"])
}
context "saving experiment" do
let(:same_but_different_goals) { Split::ExperimentCatalog.find_or_create({ "link_color" => ["purchase", "refund"] }, "blue", "red", "green") }
before { experiment.save }
it "can find existing experiment" do
expect(Split::ExperimentCatalog.find("link_color").name).to eq("link_color")
end
it "should reset an experiment if it is loaded with different goals" do
same_but_different_goals
expect(Split::ExperimentCatalog.find("link_color").goals).to eq(["purchase", "refund"])
end
end
it "should have goals" do
expect(experiment.goals).to eq(["purchase"])
end
context "find or create experiment" do
it "should have correct goals" do
experiment = Split::ExperimentCatalog.find_or_create({ "link_color3" => ["purchase", "refund"] }, "blue", "red", "green")
expect(experiment.goals).to eq(["purchase", "refund"])
experiment = Split::ExperimentCatalog.find_or_create("link_color3", "blue", "red", "green")
expect(experiment.goals).to eq([])
end
end
end
describe "beta probability calculation" do
it "should return a hash with the probability of each alternative being the best" do
experiment = Split::ExperimentCatalog.find_or_create("mathematicians", "bernoulli", "poisson", "lagrange")
experiment.calc_winning_alternatives
expect(experiment.alternative_probabilities).not_to be_nil
end
it "should return between 46% and 54% probability for an experiment with 2 alternatives and no data" do
experiment = Split::ExperimentCatalog.find_or_create("scientists", "einstein", "bohr")
experiment.calc_winning_alternatives
expect(experiment.alternatives[0].p_winner).to be_within(0.04).of(0.50)
end
it "should calculate the probability of being the winning alternative separately for each goal", skip: true do
experiment = Split::ExperimentCatalog.find_or_create({ "link_color3" => ["purchase", "refund"] }, "blue", "red", "green")
goal1 = experiment.goals[0]
goal2 = experiment.goals[1]
experiment.alternatives.each do |alternative|
alternative.participant_count = 50
alternative.set_completed_count(10, goal1)
alternative.set_completed_count(15+rand(30), goal2)
end
experiment.calc_winning_alternatives
alt = experiment.alternatives[0]
p_goal1 = alt.p_winner(goal1)
p_goal2 = alt.p_winner(goal2)
expect(p_goal1).not_to be_within(0.04).of(p_goal2)
end
it "should return nil and not re-calculate probabilities if they have already been calculated today" do
experiment = Split::ExperimentCatalog.find_or_create({ "link_color3" => ["purchase", "refund"] }, "blue", "red", "green")
expect(experiment.calc_winning_alternatives).not_to be nil
expect(experiment.calc_winning_alternatives).to be nil
end
end
end
<MSG> Merge pull request #633 from splitrb/fix-metadata-updates
Removes metadata key when it updated to nil
<DFF> @@ -151,10 +151,23 @@ describe Split::Experiment do
describe '#metadata' do
let(:experiment) { Split::Experiment.new('basket_text', :alternatives => ['Basket', "Cart"], :algorithm => Split::Algorithms::Whiplash, :metadata => meta) }
+ let(:meta) { { a: 'b' }}
+
+ before do
+ experiment.save
+ end
+
+ it "should delete the key when metadata is removed" do
+ experiment.metadata = nil
+ experiment.save
+
+ expect(Split.redis.exists?(experiment.metadata_key)).to be_falsey
+ end
+
context 'simple hash' do
let(:meta) { { 'basket' => 'a', 'cart' => 'b' } }
+
it "should persist metadata in redis" do
- experiment.save
e = Split::ExperimentCatalog.find('basket_text')
expect(e).to eq(experiment)
expect(e.metadata).to eq(meta)
@@ -164,7 +177,6 @@ describe Split::Experiment do
context 'nested hash' do
let(:meta) { { 'basket' => { 'one' => 'two' }, 'cart' => 'b' } }
it "should persist metadata in redis" do
- experiment.save
e = Split::ExperimentCatalog.find('basket_text')
expect(e).to eq(experiment)
expect(e.metadata).to eq(meta)
@@ -436,6 +448,21 @@ describe Split::Experiment do
expect(same_experiment_again.version).to eq(1)
end
+ context "when metadata is changed" do
+ it "should increase version" do
+ experiment.save
+ experiment.metadata = { 'foo' => 'bar' }
+
+ expect { experiment.save }.to change { experiment.version }.by(1)
+ end
+
+ it "does not increase version" do
+ experiment.metadata = nil
+ experiment.save
+ expect { experiment.save }.to change { experiment.version }.by(0)
+ end
+ end
+
context 'when experiment configuration is changed' do
let(:reset_manually) { false }
| 29 | Merge pull request #633 from splitrb/fix-metadata-updates | 2 | .rb | rb | mit | splitrb/split |
10071915 | <NME> split.gemspec
<BEF> # -*- encoding: utf-8 -*-
# frozen_string_literal: true
$:.push File.expand_path("../lib", __FILE__)
require "split/version"
Gem::Specification.new do |s|
s.name = "split"
s.version = Split::VERSION
s.platform = Gem::Platform::RUBY
s.authors = ["Andrew Nesbitt"]
s.licenses = ["MIT"]
s.email = ["[email protected]"]
s.homepage = "https://github.com/splitrb/split"
s.summary = "Rack based split testing framework"
s.metadata = {
"homepage_uri" => "https://github.com/splitrb/split",
"changelog_uri" => "https://github.com/splitrb/split/blob/main/CHANGELOG.md",
"source_code_uri" => "https://github.com/splitrb/split",
"bug_tracker_uri" => "https://github.com/splitrb/split/issues",
"wiki_uri" => "https://github.com/splitrb/split/wiki",
"mailing_list_uri" => "https://groups.google.com/d/forum/split-ruby"
}
s.required_ruby_version = ">= 2.5.0"
s.add_development_dependency 'bundler', '~> 1.6'
s.add_development_dependency 'coveralls'
s.add_development_dependency 'debugger'
s.add_development_dependency 'rack-test'
s.add_development_dependency 'rake'
s.add_development_dependency 'rspec', '~> 3.0'
s.add_dependency "redis", ">= 4.2"
s.add_dependency "sinatra", ">= 1.2.6"
s.add_dependency "rubystats", ">= 0.3.0"
s.add_development_dependency "bundler", ">= 1.17"
s.add_development_dependency "simplecov", "~> 0.15"
s.add_development_dependency "rack-test", "~> 2.0"
s.add_development_dependency "rake", "~> 13"
s.add_development_dependency "rspec", "~> 3.7"
s.add_development_dependency "pry", "~> 0.10"
s.add_development_dependency "rails", ">= 5.0"
end
<MSG> Fix debugger gem for Travis CI
<DFF> @@ -27,7 +27,6 @@ Gem::Specification.new do |s|
s.add_development_dependency 'bundler', '~> 1.6'
s.add_development_dependency 'coveralls'
- s.add_development_dependency 'debugger'
s.add_development_dependency 'rack-test'
s.add_development_dependency 'rake'
s.add_development_dependency 'rspec', '~> 3.0'
| 0 | Fix debugger gem for Travis CI | 1 | .gemspec | gemspec | mit | splitrb/split |
10071916 | <NME> split.gemspec
<BEF> # -*- encoding: utf-8 -*-
# frozen_string_literal: true
$:.push File.expand_path("../lib", __FILE__)
require "split/version"
Gem::Specification.new do |s|
s.name = "split"
s.version = Split::VERSION
s.platform = Gem::Platform::RUBY
s.authors = ["Andrew Nesbitt"]
s.licenses = ["MIT"]
s.email = ["[email protected]"]
s.homepage = "https://github.com/splitrb/split"
s.summary = "Rack based split testing framework"
s.metadata = {
"homepage_uri" => "https://github.com/splitrb/split",
"changelog_uri" => "https://github.com/splitrb/split/blob/main/CHANGELOG.md",
"source_code_uri" => "https://github.com/splitrb/split",
"bug_tracker_uri" => "https://github.com/splitrb/split/issues",
"wiki_uri" => "https://github.com/splitrb/split/wiki",
"mailing_list_uri" => "https://groups.google.com/d/forum/split-ruby"
}
s.required_ruby_version = ">= 2.5.0"
s.add_development_dependency 'bundler', '~> 1.6'
s.add_development_dependency 'coveralls'
s.add_development_dependency 'debugger'
s.add_development_dependency 'rack-test'
s.add_development_dependency 'rake'
s.add_development_dependency 'rspec', '~> 3.0'
s.add_dependency "redis", ">= 4.2"
s.add_dependency "sinatra", ">= 1.2.6"
s.add_dependency "rubystats", ">= 0.3.0"
s.add_development_dependency "bundler", ">= 1.17"
s.add_development_dependency "simplecov", "~> 0.15"
s.add_development_dependency "rack-test", "~> 2.0"
s.add_development_dependency "rake", "~> 13"
s.add_development_dependency "rspec", "~> 3.7"
s.add_development_dependency "pry", "~> 0.10"
s.add_development_dependency "rails", ">= 5.0"
end
<MSG> Fix debugger gem for Travis CI
<DFF> @@ -27,7 +27,6 @@ Gem::Specification.new do |s|
s.add_development_dependency 'bundler', '~> 1.6'
s.add_development_dependency 'coveralls'
- s.add_development_dependency 'debugger'
s.add_development_dependency 'rack-test'
s.add_development_dependency 'rake'
s.add_development_dependency 'rspec', '~> 3.0'
| 0 | Fix debugger gem for Travis CI | 1 | .gemspec | gemspec | mit | splitrb/split |
10071917 | <NME> split.gemspec
<BEF> # -*- encoding: utf-8 -*-
# frozen_string_literal: true
$:.push File.expand_path("../lib", __FILE__)
require "split/version"
Gem::Specification.new do |s|
s.name = "split"
s.version = Split::VERSION
s.platform = Gem::Platform::RUBY
s.authors = ["Andrew Nesbitt"]
s.licenses = ["MIT"]
s.email = ["[email protected]"]
s.homepage = "https://github.com/splitrb/split"
s.summary = "Rack based split testing framework"
s.metadata = {
"homepage_uri" => "https://github.com/splitrb/split",
"changelog_uri" => "https://github.com/splitrb/split/blob/main/CHANGELOG.md",
"source_code_uri" => "https://github.com/splitrb/split",
"bug_tracker_uri" => "https://github.com/splitrb/split/issues",
"wiki_uri" => "https://github.com/splitrb/split/wiki",
"mailing_list_uri" => "https://groups.google.com/d/forum/split-ruby"
}
s.required_ruby_version = ">= 2.5.0"
s.add_development_dependency 'bundler', '~> 1.6'
s.add_development_dependency 'coveralls'
s.add_development_dependency 'debugger'
s.add_development_dependency 'rack-test'
s.add_development_dependency 'rake'
s.add_development_dependency 'rspec', '~> 3.0'
s.add_dependency "redis", ">= 4.2"
s.add_dependency "sinatra", ">= 1.2.6"
s.add_dependency "rubystats", ">= 0.3.0"
s.add_development_dependency "bundler", ">= 1.17"
s.add_development_dependency "simplecov", "~> 0.15"
s.add_development_dependency "rack-test", "~> 2.0"
s.add_development_dependency "rake", "~> 13"
s.add_development_dependency "rspec", "~> 3.7"
s.add_development_dependency "pry", "~> 0.10"
s.add_development_dependency "rails", ">= 5.0"
end
<MSG> Fix debugger gem for Travis CI
<DFF> @@ -27,7 +27,6 @@ Gem::Specification.new do |s|
s.add_development_dependency 'bundler', '~> 1.6'
s.add_development_dependency 'coveralls'
- s.add_development_dependency 'debugger'
s.add_development_dependency 'rack-test'
s.add_development_dependency 'rake'
s.add_development_dependency 'rspec', '~> 3.0'
| 0 | Fix debugger gem for Travis CI | 1 | .gemspec | gemspec | mit | splitrb/split |
10071918 | <NME> split.gemspec
<BEF> # -*- encoding: utf-8 -*-
# frozen_string_literal: true
$:.push File.expand_path("../lib", __FILE__)
require "split/version"
Gem::Specification.new do |s|
s.name = "split"
s.version = Split::VERSION
s.platform = Gem::Platform::RUBY
s.authors = ["Andrew Nesbitt"]
s.licenses = ["MIT"]
s.email = ["[email protected]"]
s.homepage = "https://github.com/splitrb/split"
s.summary = "Rack based split testing framework"
s.metadata = {
"homepage_uri" => "https://github.com/splitrb/split",
"changelog_uri" => "https://github.com/splitrb/split/blob/main/CHANGELOG.md",
"source_code_uri" => "https://github.com/splitrb/split",
"bug_tracker_uri" => "https://github.com/splitrb/split/issues",
"wiki_uri" => "https://github.com/splitrb/split/wiki",
"mailing_list_uri" => "https://groups.google.com/d/forum/split-ruby"
}
s.add_dependency 'sinatra', '>= 1.2.6'
s.add_dependency 'simple-random'
# Ruby 1.8 doesn't include JSON in the std lib
if RUBY_VERSION < "1.9"
s.add_dependency 'json', '>= 1.7.7'
end
s.add_development_dependency 'rake'
s.add_development_dependency 'bundler', '~> 1.6'
s.add_development_dependency 'rspec', '~> 3.0'
s.require_paths = ["lib"]
s.add_dependency "redis", ">= 4.2"
s.add_dependency "sinatra", ">= 1.2.6"
s.add_dependency "rubystats", ">= 0.3.0"
s.add_development_dependency "bundler", ">= 1.17"
s.add_development_dependency "simplecov", "~> 0.15"
s.add_development_dependency "rack-test", "~> 2.0"
s.add_development_dependency "rake", "~> 13"
s.add_development_dependency "rspec", "~> 3.7"
s.add_development_dependency "pry", "~> 0.10"
s.add_development_dependency "rails", ">= 5.0"
end
<MSG> Drop 1.8 json gemspec check
<DFF> @@ -25,11 +25,6 @@ Gem::Specification.new do |s|
s.add_dependency 'sinatra', '>= 1.2.6'
s.add_dependency 'simple-random'
- # Ruby 1.8 doesn't include JSON in the std lib
- if RUBY_VERSION < "1.9"
- s.add_dependency 'json', '>= 1.7.7'
- end
-
s.add_development_dependency 'rake'
s.add_development_dependency 'bundler', '~> 1.6'
s.add_development_dependency 'rspec', '~> 3.0'
| 0 | Drop 1.8 json gemspec check | 5 | .gemspec | gemspec | mit | splitrb/split |
10071919 | <NME> split.gemspec
<BEF> # -*- encoding: utf-8 -*-
# frozen_string_literal: true
$:.push File.expand_path("../lib", __FILE__)
require "split/version"
Gem::Specification.new do |s|
s.name = "split"
s.version = Split::VERSION
s.platform = Gem::Platform::RUBY
s.authors = ["Andrew Nesbitt"]
s.licenses = ["MIT"]
s.email = ["[email protected]"]
s.homepage = "https://github.com/splitrb/split"
s.summary = "Rack based split testing framework"
s.metadata = {
"homepage_uri" => "https://github.com/splitrb/split",
"changelog_uri" => "https://github.com/splitrb/split/blob/main/CHANGELOG.md",
"source_code_uri" => "https://github.com/splitrb/split",
"bug_tracker_uri" => "https://github.com/splitrb/split/issues",
"wiki_uri" => "https://github.com/splitrb/split/wiki",
"mailing_list_uri" => "https://groups.google.com/d/forum/split-ruby"
}
s.add_dependency 'sinatra', '>= 1.2.6'
s.add_dependency 'simple-random'
# Ruby 1.8 doesn't include JSON in the std lib
if RUBY_VERSION < "1.9"
s.add_dependency 'json', '>= 1.7.7'
end
s.add_development_dependency 'rake'
s.add_development_dependency 'bundler', '~> 1.6'
s.add_development_dependency 'rspec', '~> 3.0'
s.require_paths = ["lib"]
s.add_dependency "redis", ">= 4.2"
s.add_dependency "sinatra", ">= 1.2.6"
s.add_dependency "rubystats", ">= 0.3.0"
s.add_development_dependency "bundler", ">= 1.17"
s.add_development_dependency "simplecov", "~> 0.15"
s.add_development_dependency "rack-test", "~> 2.0"
s.add_development_dependency "rake", "~> 13"
s.add_development_dependency "rspec", "~> 3.7"
s.add_development_dependency "pry", "~> 0.10"
s.add_development_dependency "rails", ">= 5.0"
end
<MSG> Drop 1.8 json gemspec check
<DFF> @@ -25,11 +25,6 @@ Gem::Specification.new do |s|
s.add_dependency 'sinatra', '>= 1.2.6'
s.add_dependency 'simple-random'
- # Ruby 1.8 doesn't include JSON in the std lib
- if RUBY_VERSION < "1.9"
- s.add_dependency 'json', '>= 1.7.7'
- end
-
s.add_development_dependency 'rake'
s.add_development_dependency 'bundler', '~> 1.6'
s.add_development_dependency 'rspec', '~> 3.0'
| 0 | Drop 1.8 json gemspec check | 5 | .gemspec | gemspec | mit | splitrb/split |
10071920 | <NME> split.gemspec
<BEF> # -*- encoding: utf-8 -*-
# frozen_string_literal: true
$:.push File.expand_path("../lib", __FILE__)
require "split/version"
Gem::Specification.new do |s|
s.name = "split"
s.version = Split::VERSION
s.platform = Gem::Platform::RUBY
s.authors = ["Andrew Nesbitt"]
s.licenses = ["MIT"]
s.email = ["[email protected]"]
s.homepage = "https://github.com/splitrb/split"
s.summary = "Rack based split testing framework"
s.metadata = {
"homepage_uri" => "https://github.com/splitrb/split",
"changelog_uri" => "https://github.com/splitrb/split/blob/main/CHANGELOG.md",
"source_code_uri" => "https://github.com/splitrb/split",
"bug_tracker_uri" => "https://github.com/splitrb/split/issues",
"wiki_uri" => "https://github.com/splitrb/split/wiki",
"mailing_list_uri" => "https://groups.google.com/d/forum/split-ruby"
}
s.add_dependency 'sinatra', '>= 1.2.6'
s.add_dependency 'simple-random'
# Ruby 1.8 doesn't include JSON in the std lib
if RUBY_VERSION < "1.9"
s.add_dependency 'json', '>= 1.7.7'
end
s.add_development_dependency 'rake'
s.add_development_dependency 'bundler', '~> 1.6'
s.add_development_dependency 'rspec', '~> 3.0'
s.require_paths = ["lib"]
s.add_dependency "redis", ">= 4.2"
s.add_dependency "sinatra", ">= 1.2.6"
s.add_dependency "rubystats", ">= 0.3.0"
s.add_development_dependency "bundler", ">= 1.17"
s.add_development_dependency "simplecov", "~> 0.15"
s.add_development_dependency "rack-test", "~> 2.0"
s.add_development_dependency "rake", "~> 13"
s.add_development_dependency "rspec", "~> 3.7"
s.add_development_dependency "pry", "~> 0.10"
s.add_development_dependency "rails", ">= 5.0"
end
<MSG> Drop 1.8 json gemspec check
<DFF> @@ -25,11 +25,6 @@ Gem::Specification.new do |s|
s.add_dependency 'sinatra', '>= 1.2.6'
s.add_dependency 'simple-random'
- # Ruby 1.8 doesn't include JSON in the std lib
- if RUBY_VERSION < "1.9"
- s.add_dependency 'json', '>= 1.7.7'
- end
-
s.add_development_dependency 'rake'
s.add_development_dependency 'bundler', '~> 1.6'
s.add_development_dependency 'rspec', '~> 3.0'
| 0 | Drop 1.8 json gemspec check | 5 | .gemspec | gemspec | mit | splitrb/split |
10071921 | <NME> transducers.js
<BEF>
// basic protocol helpers
var symbolExists = typeof Symbol !== 'undefined';
var protocols = {
iterator: symbolExists ? Symbol.iterator : '@@iterator'
};
function throwProtocolError(name, coll) {
throw new Error("don't know how to " + name + " collection: " +
coll);
}
function fulfillsProtocol(obj, name) {
if(name === 'iterator') {
// Accept ill-formed iterators that don't conform to the
// protocol by accepting just next()
return obj[protocols.iterator] || obj.next;
}
return obj[protocols[name]];
}
function getProtocolProperty(obj, name) {
return obj[protocols[name]];
}
function iterator(coll) {
var iter = getProtocolProperty(coll, 'iterator');
if(iter) {
return iter.call(coll);
}
else if(coll.next) {
// Basic duck typing to accept an ill-formed iterator that doesn't
// conform to the iterator protocol (all iterators should have the
// @@iterator method and return themselves, but some engines don't
// have that on generators like older v8)
return coll;
}
else if(isArray(coll)) {
return new ArrayIterator(coll);
}
else if(isObject(coll)) {
return new ObjectIterator(coll);
}
}
function ArrayIterator(arr) {
this.arr = arr;
this.index = 0;
}
ArrayIterator.prototype.next = function() {
if(this.index < this.arr.length) {
return {
value: this.arr[this.index++],
done: false
};
}
function isArray(x) {
return x instanceof Array;
}
function isFunction(x) {
return typeof x === 'function';
ObjectIterator.prototype.next = function() {
if(this.index < this.keys.length) {
var k = this.keys[this.index++];
return {
value: [k, this.obj[k]],
done: false
};
}
return {
done: true
}
};
// helpers
var toString = Object.prototype.toString;
var isArray = typeof Array.isArray === 'function' ? Array.isArray : function(obj) {
return toString.call(obj) == '[object Array]';
};
function isFunction(x) {
return typeof x === 'function';
}
function isObject(x) {
return x instanceof Object &&
Object.getPrototypeOf(x) === Object.getPrototypeOf({});
}
function isNumber(x) {
return typeof x === 'number';
}
function Reduced(value) {
this['@@transducer/reduced'] = true;
this['@@transducer/value'] = value;
}
function isReduced(x) {
return (x instanceof Reduced) || (x && x['@@transducer/reduced']);
}
function deref(x) {
return x['@@transducer/value'];
}
/**
* This is for transforms that may call their nested transforms before
* Reduced-wrapping the result (e.g. "take"), to avoid nested Reduced.
*/
function ensureReduced(val) {
if(isReduced(val)) {
return val;
} else {
return new Reduced(val);
}
}
/**
* This is for tranforms that call their nested transforms when
* performing completion (like "partition"), to avoid signaling
* termination after already completing.
*/
function ensureUnreduced(v) {
if(isReduced(v)) {
return deref(v);
} else {
return v;
}
}
function reduce(coll, xform, init) {
if(isArray(coll)) {
var result = init;
var index = -1;
var len = coll.length;
while(++index < len) {
result = xform['@@transducer/step'](result, coll[index]);
if(isReduced(result)) {
result = deref(result);
break;
}
}
return xform['@@transducer/result'](result);
}
else if(isObject(coll) || fulfillsProtocol(coll, 'iterator')) {
var result = init;
var iter = iterator(coll);
var val = iter.next();
while(!val.done) {
result = xform['@@transducer/step'](result, val.value);
if(isReduced(result)) {
result = deref(result);
break;
}
val = iter.next();
}
return xform['@@transducer/result'](result);
}
throwProtocolError('iterate', coll);
}
function transduce(coll, xform, reducer, init) {
xform = xform(reducer);
if(init === undefined) {
init = xform['@@transducer/init']();
}
return reduce(coll, xform, init);
}
function compose() {
var funcs = Array.prototype.slice.call(arguments);
return function(r) {
var value = r;
for(var i=funcs.length-1; i>=0; i--) {
value = funcs[i](value);
}
return value;
}
}
// transformations
function transformer(f) {
var t = {};
t['@@transducer/init'] = function() {
throw new Error('init value unavailable');
};
t['@@transducer/result'] = function(v) {
return v;
};
t['@@transducer/step'] = f;
return t;
}
function bound(f, ctx, count) {
count = count != null ? count : 1;
if(!ctx) {
return f;
}
else {
switch(count) {
case 1:
return function(x) {
return f.call(ctx, x);
}
case 2:
return function(x, y) {
return f.call(ctx, x, y);
}
default:
return f.bind(ctx);
}
}
}
function arrayMap(arr, f, ctx) {
var index = -1;
var length = arr.length;
var result = Array(length);
f = bound(f, ctx, 2);
while (++index < length) {
result[index] = f(arr[index], index);
}
return result;
}
function arrayFilter(arr, f, ctx) {
var len = arr.length;
var result = [];
f = bound(f, ctx, 2);
for(var i=0; i<len; i++) {
if(f(arr[i], i)) {
result.push(arr[i]);
}
}
return result;
}
function Map(f, xform) {
this.xform = xform;
this.f = f;
}
Map.prototype['@@transducer/init'] = function() {
return this.xform['@@transducer/init']();
};
Map.prototype['@@transducer/result'] = function(v) {
return this.xform['@@transducer/result'](v);
};
Map.prototype['@@transducer/step'] = function(res, input) {
return this.xform['@@transducer/step'](res, this.f(input));
};
function map(coll, f, ctx) {
if(isFunction(coll)) { ctx = f; f = coll; coll = null; }
f = bound(f, ctx);
if(coll) {
if(isArray(coll)) {
return arrayMap(coll, f, ctx);
}
return seq(coll, map(f));
}
return function(xform) {
return new Map(f, xform);
}
}
function Filter(f, xform) {
this.xform = xform;
this.f = f;
}
Filter.prototype['@@transducer/init'] = function() {
return this.xform['@@transducer/init']();
};
Filter.prototype['@@transducer/result'] = function(v) {
return this.xform['@@transducer/result'](v);
};
Filter.prototype['@@transducer/step'] = function(res, input) {
if(this.f(input)) {
return this.xform['@@transducer/step'](res, input);
}
return res;
};
function filter(coll, f, ctx) {
if(isFunction(coll)) { ctx = f; f = coll; coll = null; }
f = bound(f, ctx);
if(coll) {
if(isArray(coll)) {
return arrayFilter(coll, f, ctx);
}
return seq(coll, filter(f));
}
return function(xform) {
return new Filter(f, xform);
};
}
function remove(coll, f, ctx) {
if(isFunction(coll)) { ctx = f; f = coll; coll = null; }
f = bound(f, ctx);
return filter(coll, function(x) { return !f(x); });
}
function keep(coll) {
return filter(coll, function(x) { return x != null });
}
function Dedupe(xform) {
this.xform = xform;
this.last = undefined;
}
Dedupe.prototype['@@transducer/init'] = function() {
return this.xform['@@transducer/init']();
};
Dedupe.prototype['@@transducer/result'] = function(v) {
return this.xform['@@transducer/result'](v);
};
Dedupe.prototype['@@transducer/step'] = function(result, input) {
if(input !== this.last) {
this.last = input;
return this.xform['@@transducer/step'](result, input);
}
return result;
};
function dedupe(coll) {
if(coll) {
return seq(coll, dedupe());
}
return function(xform) {
return new Dedupe(xform);
}
}
function TakeWhile(f, xform) {
this.xform = xform;
this.f = f;
}
TakeWhile.prototype['@@transducer/init'] = function() {
return this.xform['@@transducer/init']();
};
TakeWhile.prototype['@@transducer/result'] = function(v) {
return this.xform['@@transducer/result'](v);
};
TakeWhile.prototype['@@transducer/step'] = function(result, input) {
if(this.f(input)) {
return this.xform['@@transducer/step'](result, input);
}
return new Reduced(result);
};
function takeWhile(coll, f, ctx) {
if(isFunction(coll)) { ctx = f; f = coll; coll = null; }
f = bound(f, ctx);
if(coll) {
return seq(coll, takeWhile(f));
}
return function(xform) {
return new TakeWhile(f, xform);
}
}
function Take(n, xform) {
this.n = n;
this.i = 0;
this.xform = xform;
}
Take.prototype['@@transducer/init'] = function() {
return this.xform['@@transducer/init']();
};
Take.prototype['@@transducer/result'] = function(v) {
return this.xform['@@transducer/result'](v);
};
Take.prototype['@@transducer/step'] = function(result, input) {
if (this.i < this.n) {
result = this.xform['@@transducer/step'](result, input);
if(this.i + 1 >= this.n) {
// Finish reducing on the same step as the final value. TODO:
// double-check that this doesn't break any semantics
result = ensureReduced(result);
}
}
this.i++;
return result;
};
function take(coll, n) {
if(isNumber(coll)) { n = coll; coll = null }
if(coll) {
return seq(coll, take(n));
}
return function(xform) {
return new Take(n, xform);
}
}
function Drop(n, xform) {
this.n = n;
this.i = 0;
this.xform = xform;
}
Drop.prototype['@@transducer/init'] = function() {
return this.xform['@@transducer/init']();
};
Drop.prototype['@@transducer/result'] = function(v) {
return this.xform['@@transducer/result'](v);
};
Drop.prototype['@@transducer/step'] = function(result, input) {
if(this.i++ < this.n) {
return result;
}
return this.xform['@@transducer/step'](result, input);
};
function drop(coll, n) {
if(isNumber(coll)) { n = coll; coll = null }
if(coll) {
return seq(coll, drop(n));
}
return function(xform) {
return new Drop(n, xform);
}
}
function DropWhile(f, xform) {
this.xform = xform;
this.f = f;
this.dropping = true;
}
DropWhile.prototype['@@transducer/init'] = function() {
return this.xform['@@transducer/init']();
};
DropWhile.prototype['@@transducer/result'] = function(v) {
return this.xform['@@transducer/result'](v);
};
DropWhile.prototype['@@transducer/step'] = function(result, input) {
if(this.dropping) {
if(this.f(input)) {
return result;
}
else {
this.dropping = false;
}
}
return this.xform['@@transducer/step'](result, input);
};
function dropWhile(coll, f, ctx) {
if(isFunction(coll)) { ctx = f; f = coll; coll = null; }
f = bound(f, ctx);
if(coll) {
return seq(coll, dropWhile(f));
}
return function(xform) {
return new DropWhile(f, xform);
}
}
function Partition(n, xform) {
this.n = n;
this.i = 0;
this.xform = xform;
this.part = new Array(n);
}
Partition.prototype['@@transducer/init'] = function() {
return this.xform['@@transducer/init']();
};
Partition.prototype['@@transducer/result'] = function(v) {
if (this.i > 0) {
return ensureUnreduced(this.xform['@@transducer/step'](v, this.part.slice(0, this.i)));
}
return this.xform['@@transducer/result'](v);
};
Partition.prototype['@@transducer/step'] = function(result, input) {
this.part[this.i] = input;
this.i += 1;
if (this.i === this.n) {
var out = this.part.slice(0, this.n);
this.part = new Array(this.n);
this.i = 0;
return this.xform['@@transducer/step'](result, out);
}
return result;
};
function partition(coll, n) {
if (isNumber(coll)) {
n = coll; coll = null;
}
if (coll) {
return seq(coll, partition(n));
}
return function(xform) {
return new Partition(n, xform);
};
}
var NOTHING = {};
function PartitionBy(f, xform) {
// TODO: take an "opts" object that allows the user to specify
// equality
this.f = f;
this.xform = xform;
this.part = [];
this.last = NOTHING;
}
PartitionBy.prototype['@@transducer/init'] = function() {
return this.xform['@@transducer/init']();
};
PartitionBy.prototype['@@transducer/result'] = function(v) {
var l = this.part.length;
if (l > 0) {
return ensureUnreduced(this.xform['@@transducer/step'](v, this.part.slice(0, l)));
}
return this.xform['@@transducer/result'](v);
};
PartitionBy.prototype['@@transducer/step'] = function(result, input) {
var current = this.f(input);
if (current === this.last || this.last === NOTHING) {
this.part.push(input);
} else {
result = this.xform['@@transducer/step'](result, this.part);
this.part = [input];
}
this.last = current;
return result;
};
function partitionBy(coll, f, ctx) {
if (isFunction(coll)) { ctx = f; f = coll; coll = null; }
f = bound(f, ctx);
if (coll) {
return seq(coll, partitionBy(f));
}
return function(xform) {
return new PartitionBy(f, xform);
};
}
function Interpose(sep, xform) {
this.sep = sep;
this.xform = xform;
this.started = false;
}
Interpose.prototype['@@transducer/init'] = function() {
return this.xform['@@transducer/init']();
};
Interpose.prototype['@@transducer/result'] = function(v) {
return this.xform['@@transducer/result'](v);
};
Interpose.prototype['@@transducer/step'] = function(result, input) {
if (this.started) {
var withSep = this.xform['@@transducer/step'](result, this.sep);
if (isReduced(withSep)) {
return withSep;
} else {
return this.xform['@@transducer/step'](withSep, input);
}
} else {
this.started = true;
return this.xform['@@transducer/step'](result, input);
}
};
/**
* Returns a new collection containing elements of the given
* collection, separated by the specified separator. Returns a
* transducer if a collection is not provided.
*/
function interpose(coll, separator) {
if (arguments.length === 1) {
separator = coll;
return function(xform) {
return new Interpose(separator, xform);
};
}
return seq(coll, interpose(separator));
}
function Repeat(n, xform) {
this.xform = xform;
this.n = n;
}
Repeat.prototype['@@transducer/init'] = function() {
return this.xform['@@transducer/init']();
};
Repeat.prototype['@@transducer/result'] = function(v) {
return this.xform['@@transducer/result'](v);
};
Repeat.prototype['@@transducer/step'] = function(result, input) {
var n = this.n;
var r = result;
for (var i = 0; i < n; i++) {
r = this.xform['@@transducer/step'](r, input);
if (isReduced(r)) {
break;
}
}
return r;
};
/**
* Returns a new collection containing elements of the given
* collection, each repeated n times. Returns a transducer if a
* collection is not provided.
*/
function repeat(coll, n) {
if (arguments.length === 1) {
n = coll;
return function(xform) {
return new Repeat(n, xform);
};
}
return seq(coll, repeat(n));
}
function TakeNth(n, xform) {
this.xform = xform;
this.n = n;
this.i = -1;
}
TakeNth.prototype['@@transducer/init'] = function() {
return this.xform['@@transducer/init']();
};
TakeNth.prototype['@@transducer/result'] = function(v) {
return this.xform['@@transducer/result'](v);
};
TakeNth.prototype['@@transducer/step'] = function(result, input) {
this.i += 1;
if (this.i % this.n === 0) {
return this.xform['@@transducer/step'](result, input);
}
return result;
};
/**
* Returns a new collection of every nth element of the given
* collection. Returns a transducer if a collection is not provided.
*/
function takeNth(coll, nth) {
if (arguments.length === 1) {
nth = coll;
return function(xform) {
return new TakeNth(nth, xform);
};
}
return seq(coll, takeNth(nth));
}
// pure transducers (cannot take collections)
function Cat(xform) {
this.xform = xform;
}
Cat.prototype['@@transducer/init'] = function() {
return this.xform['@@transducer/init']();
};
Cat.prototype['@@transducer/result'] = function(v) {
return this.xform['@@transducer/result'](v);
};
Cat.prototype['@@transducer/step'] = function(result, input) {
var xform = this.xform;
var newxform = {};
newxform['@@transducer/init'] = function() {
return xform['@@transducer/init']();
};
newxform['@@transducer/result'] = function(v) {
return v;
};
newxform['@@transducer/step'] = function(result, input) {
var val = xform['@@transducer/step'](result, input);
return isReduced(val) ? deref(val) : val;
};
return reduce(input, newxform, result);
};
function cat(xform) {
return new Cat(xform);
}
function mapcat(f, ctx) {
f = bound(f, ctx);
return compose(map(f), cat);
}
// collection helpers
function push(arr, x) {
arr.push(x);
return arr;
}
function merge(obj, x) {
if(isArray(x) && x.length === 2) {
obj[x[0]] = x[1];
}
else {
var keys = Object.keys(x);
var len = keys.length;
for(var i=0; i<len; i++) {
obj[keys[i]] = x[keys[i]];
}
}
return obj;
}
var arrayReducer = {};
arrayReducer['@@transducer/init'] = function() {
return [];
};
arrayReducer['@@transducer/result'] = function(v) {
return v;
};
arrayReducer['@@transducer/step'] = push;
var objReducer = {};
objReducer['@@transducer/init'] = function() {
return {};
};
objReducer['@@transducer/result'] = function(v) {
return v;
};
objReducer['@@transducer/step'] = merge;
// building new collections
function toArray(coll, xform) {
if(!xform) {
return reduce(coll, arrayReducer, []);
}
return transduce(coll, xform, arrayReducer, []);
}
function toObj(coll, xform) {
if(!xform) {
return reduce(coll, objReducer, {});
}
return transduce(coll, xform, objReducer, {});
}
function toIter(coll, xform) {
if(!xform) {
return iterator(coll);
}
return new LazyTransformer(xform, coll);
}
function seq(coll, xform) {
if(isArray(coll)) {
return transduce(coll, xform, arrayReducer, []);
}
else if(isObject(coll)) {
return transduce(coll, xform, objReducer, {});
}
else if(coll['@@transducer/step']) {
var init;
if(coll['@@transducer/init']) {
init = coll['@@transducer/init']();
}
else {
init = new coll.constructor();
}
return transduce(coll, xform, coll, init);
}
else if(fulfillsProtocol(coll, 'iterator')) {
return new LazyTransformer(xform, coll);
}
throwProtocolError('sequence', coll);
}
function into(to, xform, from) {
if(isArray(to)) {
return transduce(from, xform, arrayReducer, to);
}
else if(isObject(to)) {
return transduce(from, xform, objReducer, to);
}
else if(to['@@transducer/step']) {
return transduce(from,
xform,
to,
to);
}
throwProtocolError('into', to);
}
// laziness
var stepper = {};
stepper['@@transducer/result'] = function(v) {
return isReduced(v) ? deref(v) : v;
};
stepper['@@transducer/step'] = function(lt, x) {
lt.items.push(x);
return lt.rest;
};
function Stepper(xform, iter) {
this.xform = xform(stepper);
this.iter = iter;
}
Stepper.prototype['@@transducer/step'] = function(lt) {
var len = lt.items.length;
while(lt.items.length === len) {
var n = this.iter.next();
if(n.done || isReduced(n.value)) {
// finalize
this.xform['@@transducer/result'](this);
break;
}
// step
this.xform['@@transducer/step'](lt, n.value);
}
}
function LazyTransformer(xform, coll) {
this.iter = iterator(coll);
this.items = [];
this.stepper = new Stepper(xform, iterator(coll));
}
LazyTransformer.prototype[protocols.iterator] = function() {
return this;
}
LazyTransformer.prototype.next = function() {
this['@@transducer/step']();
if(this.items.length) {
return {
value: this.items.pop(),
done: false
}
}
else {
return { done: true };
}
};
LazyTransformer.prototype['@@transducer/step'] = function() {
if(!this.items.length) {
this.stepper['@@transducer/step'](this);
}
}
// util
function range(n) {
var arr = new Array(n);
for(var i=0; i<arr.length; i++) {
arr[i] = i;
}
return arr;
}
module.exports = {
reduce: reduce,
transformer: transformer,
Reduced: Reduced,
isReduced: isReduced,
iterator: iterator,
push: push,
merge: merge,
transduce: transduce,
seq: seq,
toArray: toArray,
toObj: toObj,
toIter: toIter,
into: into,
compose: compose,
map: map,
filter: filter,
remove: remove,
cat: cat,
mapcat: mapcat,
keep: keep,
dedupe: dedupe,
take: take,
takeWhile: takeWhile,
takeNth: takeNth,
drop: drop,
dropWhile: dropWhile,
partition: partition,
partitionBy: partitionBy,
interpose: interpose,
repeat: repeat,
range: range,
LazyTransformer: LazyTransformer
};
<MSG> more accurate array check. As a bonus, Array.isArray (if available) is faster
<DFF> @@ -61,6 +61,10 @@ function iterator(coll) {
function isArray(x) {
return x instanceof Array;
}
+var toString = Object.prototype.toString;
+var isArray = typeof Array.isArray === 'function' ? Array.isArray : function(obj) {
+ return toString.call(obj) == '[object Array]';
+};
function isFunction(x) {
return typeof x === 'function';
| 4 | more accurate array check. As a bonus, Array.isArray (if available) is faster | 0 | .js | js | bsd-2-clause | jlongster/transducers.js |
10071922 | <NME> configuration.rb
<BEF> # frozen_string_literal: true
module Split
class Configuration
attr_accessor :ignore_ip_addresses
attr_accessor :ignore_filter
attr_accessor :db_failover
attr_accessor :db_failover_on_db_error
attr_accessor :db_failover_allow_parameter_override
attr_accessor :allow_multiple_experiments
attr_accessor :enabled
attr_accessor :persistence
attr_accessor :persistence_cookie_length
attr_accessor :persistence_cookie_domain
attr_accessor :algorithm
attr_accessor :store_override
attr_accessor :start_manually
attr_accessor :reset_manually
attr_accessor :on_trial
attr_accessor :on_trial_choose
attr_accessor :on_trial_complete
attr_accessor :on_experiment_reset
attr_accessor :on_experiment_delete
attr_accessor :on_before_experiment_reset
attr_accessor :on_experiment_winner_choose
'AdsBot-Google' => 'Google Adwords',
'Baidu' => 'Chinese search engine',
'Baiduspider' => 'Chinese search engine',
'Butterfly' => 'Topsy Labs',
'Gigabot' => 'Gigabot spider',
'Googlebot' => 'Google spider',
'msnbot' => 'Microsoft bot',
'bingbot' => 'Microsoft bing bot',
'rogerbot' => 'SeoMoz spider',
'PaperLiBot' => 'PaperLi is another content curation service',
'Slurp' => 'Yahoo spider',
def bots
@bots ||= {
# Indexers
"AdsBot-Google" => "Google Adwords",
"Baidu" => "Chinese search engine",
"Baiduspider" => "Chinese search engine",
"bingbot" => "Microsoft bing bot",
"Butterfly" => "Topsy Labs",
"Gigabot" => "Gigabot spider",
"Googlebot" => "Google spider",
"MJ12bot" => "Majestic-12 spider",
"msnbot" => "Microsoft bot",
"rogerbot" => "SeoMoz spider",
"PaperLiBot" => "PaperLi is another content curation service",
"Slurp" => "Yahoo spider",
"Sogou" => "Chinese search engine",
"spider" => "generic web spider",
"UnwindFetchor" => "Gnip crawler",
"WordPress" => "WordPress spider",
"YandexAccessibilityBot" => "Yandex accessibility spider",
"YandexBot" => "Yandex spider",
"YandexMobileBot" => "Yandex mobile spider",
"ZIBB" => "ZIBB spider",
# HTTP libraries
"Apache-HttpClient" => "Java http library",
"AppEngine-Google" => "Google App Engine",
"curl" => "curl unix CLI http client",
"ColdFusion" => "ColdFusion http library",
"EventMachine HttpClient" => "Ruby http library",
"Go http package" => "Go http library",
"Go-http-client" => "Go http library",
"Java" => "Generic Java http library",
"libwww-perl" => "Perl client-server library loved by script kids",
"lwp-trivial" => "Another Perl library loved by script kids",
"Python-urllib" => "Python http library",
"PycURL" => "Python http library",
"Test Certificate Info" => "C http library?",
"Typhoeus" => "Ruby http library",
"Wget" => "wget unix CLI http client",
# URL expanders / previewers
"awe.sm" => "Awe.sm URL expander",
"bitlybot" => "bit.ly bot",
"[email protected]" => "Linkfluence bot",
"facebookexternalhit" => "facebook bot",
"Facebot" => "Facebook crawler",
"Feedfetcher-Google" => "Google Feedfetcher",
"https://developers.google.com/+/web/snippet" => "Google+ Snippet Fetcher",
"LinkedInBot" => "LinkedIn bot",
"LongURL" => "URL expander service",
"NING" => "NING - Yet Another Twitter Swarmer",
"Pinterestbot" => "Pinterest Bot",
"redditbot" => "Reddit Bot",
"ShortLinkTranslate" => "Link shortener",
"Slackbot" => "Slackbot link expander",
"TweetmemeBot" => "TweetMeMe Crawler",
"Twitterbot" => "Twitter URL expander",
"UnwindFetch" => "Gnip URL expander",
"vkShare" => "VKontake Sharer",
# Uptime monitoring
"check_http" => "Nagios monitor",
"GoogleStackdriverMonitoring" => "Google Cloud monitor",
"NewRelicPinger" => "NewRelic monitor",
"Panopta" => "Monitoring service",
"Pingdom" => "Pingdom monitoring",
"SiteUptime" => "Site monitoring services",
"UptimeRobot" => "Monitoring service",
# ???
"DigitalPersona Fingerprint Software" => "HP Fingerprint scanner",
"ShowyouBot" => "Showyou iOS app spider",
"ZyBorg" => "Zyborg? Hmmm....",
"ELB-HealthChecker" => "ELB Health Check"
}
end
def experiments=(experiments)
raise InvalidExperimentsFormatError.new("Experiments must be a Hash") unless experiments.respond_to?(:keys)
@experiments = experiments
end
def disabled?
!enabled
end
def experiment_for(name)
if normalized_experiments
# TODO symbols
normalized_experiments[name.to_sym]
end
end
def metrics
return @metrics if defined?(@metrics)
@metrics = {}
if self.experiments
self.experiments.each do |key, value|
metrics = value_for(value, :metric) rescue nil
Array(metrics).each do |metric_name|
if metric_name
@metrics[metric_name.to_sym] ||= []
@metrics[metric_name.to_sym] << Split::Experiment.new(key)
end
end
end
end
@metrics
end
def normalized_experiments
return nil if @experiments.nil?
experiment_config = {}
@experiments.keys.each do |name|
experiment_config[name.to_sym] = {}
end
@experiments.each do |experiment_name, settings|
alternatives = if (alts = value_for(settings, :alternatives))
normalize_alternatives(alts)
end
experiment_data = {
alternatives: alternatives,
goals: value_for(settings, :goals),
metadata: value_for(settings, :metadata),
algorithm: value_for(settings, :algorithm),
resettable: value_for(settings, :resettable)
}
experiment_data.each do |name, value|
experiment_config[experiment_name.to_sym][name] = value if value != nil
end
end
experiment_config
end
def normalize_alternatives(alternatives)
given_probability, num_with_probability = alternatives.inject([0, 0]) do |a, v|
p, n = a
if percent = value_for(v, :percent)
[p + percent, n + 1]
else
a
end
end
num_without_probability = alternatives.length - num_with_probability
unassigned_probability = ((100.0 - given_probability) / num_without_probability / 100.0)
if num_with_probability.nonzero?
alternatives = alternatives.map do |v|
if (name = value_for(v, :name)) && (percent = value_for(v, :percent))
{ name => percent / 100.0 }
elsif name = value_for(v, :name)
{ name => unassigned_probability }
else
{ v => unassigned_probability }
end
end
[alternatives.shift, alternatives]
else
alternatives = alternatives.dup
[alternatives.shift, alternatives]
end
end
def robot_regex
@robot_regex ||= /\b(?:#{escaped_bots.join('|')})\b|\A\W*\z/i
end
def initialize
@ignore_ip_addresses = []
@ignore_filter = proc { |request| is_robot? || is_ignored_ip_address? }
@db_failover = false
@db_failover_on_db_error = proc { |error| } # e.g. use Rails logger here
@on_experiment_reset = proc { |experiment| }
@on_experiment_delete = proc { |experiment| }
@on_before_experiment_reset = proc { |experiment| }
@on_before_experiment_delete = proc { |experiment| }
@on_experiment_winner_choose = proc { |experiment| }
@db_failover_allow_parameter_override = false
@allow_multiple_experiments = false
@enabled = true
@experiments = {}
@persistence = Split::Persistence::SessionAdapter
@persistence_cookie_length = 31536000 # One year from now
@persistence_cookie_domain = nil
@algorithm = Split::Algorithms::WeightedSample
@include_rails_helper = true
@beta_probability_simulations = 10000
@winning_alternative_recalculation_interval = 60 * 60 * 24 # 1 day
@redis = ENV.fetch(ENV.fetch("REDIS_PROVIDER", "REDIS_URL"), "redis://localhost:6379")
@dashboard_pagination_default_per_page = 10
end
private
def value_for(hash, key)
if hash.kind_of?(Hash)
hash.has_key?(key.to_s) ? hash[key.to_s] : hash[key.to_sym]
end
end
def escaped_bots
bots.map { |key, _| Regexp.escape(key) }
end
end
end
<MSG> Added another bot.
<DFF> @@ -26,11 +26,12 @@ module Split
'AdsBot-Google' => 'Google Adwords',
'Baidu' => 'Chinese search engine',
'Baiduspider' => 'Chinese search engine',
+ 'bingbot' => 'Microsoft bing bot',
'Butterfly' => 'Topsy Labs',
'Gigabot' => 'Gigabot spider',
'Googlebot' => 'Google spider',
+ 'MJ12bot' => 'Majestic-12 spider',
'msnbot' => 'Microsoft bot',
- 'bingbot' => 'Microsoft bing bot',
'rogerbot' => 'SeoMoz spider',
'PaperLiBot' => 'PaperLi is another content curation service',
'Slurp' => 'Yahoo spider',
| 2 | Added another bot. | 1 | .rb | rb | mit | splitrb/split |
10071923 | <NME> configuration.rb
<BEF> # frozen_string_literal: true
module Split
class Configuration
attr_accessor :ignore_ip_addresses
attr_accessor :ignore_filter
attr_accessor :db_failover
attr_accessor :db_failover_on_db_error
attr_accessor :db_failover_allow_parameter_override
attr_accessor :allow_multiple_experiments
attr_accessor :enabled
attr_accessor :persistence
attr_accessor :persistence_cookie_length
attr_accessor :persistence_cookie_domain
attr_accessor :algorithm
attr_accessor :store_override
attr_accessor :start_manually
attr_accessor :reset_manually
attr_accessor :on_trial
attr_accessor :on_trial_choose
attr_accessor :on_trial_complete
attr_accessor :on_experiment_reset
attr_accessor :on_experiment_delete
attr_accessor :on_before_experiment_reset
attr_accessor :on_experiment_winner_choose
'AdsBot-Google' => 'Google Adwords',
'Baidu' => 'Chinese search engine',
'Baiduspider' => 'Chinese search engine',
'Butterfly' => 'Topsy Labs',
'Gigabot' => 'Gigabot spider',
'Googlebot' => 'Google spider',
'msnbot' => 'Microsoft bot',
'bingbot' => 'Microsoft bing bot',
'rogerbot' => 'SeoMoz spider',
'PaperLiBot' => 'PaperLi is another content curation service',
'Slurp' => 'Yahoo spider',
def bots
@bots ||= {
# Indexers
"AdsBot-Google" => "Google Adwords",
"Baidu" => "Chinese search engine",
"Baiduspider" => "Chinese search engine",
"bingbot" => "Microsoft bing bot",
"Butterfly" => "Topsy Labs",
"Gigabot" => "Gigabot spider",
"Googlebot" => "Google spider",
"MJ12bot" => "Majestic-12 spider",
"msnbot" => "Microsoft bot",
"rogerbot" => "SeoMoz spider",
"PaperLiBot" => "PaperLi is another content curation service",
"Slurp" => "Yahoo spider",
"Sogou" => "Chinese search engine",
"spider" => "generic web spider",
"UnwindFetchor" => "Gnip crawler",
"WordPress" => "WordPress spider",
"YandexAccessibilityBot" => "Yandex accessibility spider",
"YandexBot" => "Yandex spider",
"YandexMobileBot" => "Yandex mobile spider",
"ZIBB" => "ZIBB spider",
# HTTP libraries
"Apache-HttpClient" => "Java http library",
"AppEngine-Google" => "Google App Engine",
"curl" => "curl unix CLI http client",
"ColdFusion" => "ColdFusion http library",
"EventMachine HttpClient" => "Ruby http library",
"Go http package" => "Go http library",
"Go-http-client" => "Go http library",
"Java" => "Generic Java http library",
"libwww-perl" => "Perl client-server library loved by script kids",
"lwp-trivial" => "Another Perl library loved by script kids",
"Python-urllib" => "Python http library",
"PycURL" => "Python http library",
"Test Certificate Info" => "C http library?",
"Typhoeus" => "Ruby http library",
"Wget" => "wget unix CLI http client",
# URL expanders / previewers
"awe.sm" => "Awe.sm URL expander",
"bitlybot" => "bit.ly bot",
"[email protected]" => "Linkfluence bot",
"facebookexternalhit" => "facebook bot",
"Facebot" => "Facebook crawler",
"Feedfetcher-Google" => "Google Feedfetcher",
"https://developers.google.com/+/web/snippet" => "Google+ Snippet Fetcher",
"LinkedInBot" => "LinkedIn bot",
"LongURL" => "URL expander service",
"NING" => "NING - Yet Another Twitter Swarmer",
"Pinterestbot" => "Pinterest Bot",
"redditbot" => "Reddit Bot",
"ShortLinkTranslate" => "Link shortener",
"Slackbot" => "Slackbot link expander",
"TweetmemeBot" => "TweetMeMe Crawler",
"Twitterbot" => "Twitter URL expander",
"UnwindFetch" => "Gnip URL expander",
"vkShare" => "VKontake Sharer",
# Uptime monitoring
"check_http" => "Nagios monitor",
"GoogleStackdriverMonitoring" => "Google Cloud monitor",
"NewRelicPinger" => "NewRelic monitor",
"Panopta" => "Monitoring service",
"Pingdom" => "Pingdom monitoring",
"SiteUptime" => "Site monitoring services",
"UptimeRobot" => "Monitoring service",
# ???
"DigitalPersona Fingerprint Software" => "HP Fingerprint scanner",
"ShowyouBot" => "Showyou iOS app spider",
"ZyBorg" => "Zyborg? Hmmm....",
"ELB-HealthChecker" => "ELB Health Check"
}
end
def experiments=(experiments)
raise InvalidExperimentsFormatError.new("Experiments must be a Hash") unless experiments.respond_to?(:keys)
@experiments = experiments
end
def disabled?
!enabled
end
def experiment_for(name)
if normalized_experiments
# TODO symbols
normalized_experiments[name.to_sym]
end
end
def metrics
return @metrics if defined?(@metrics)
@metrics = {}
if self.experiments
self.experiments.each do |key, value|
metrics = value_for(value, :metric) rescue nil
Array(metrics).each do |metric_name|
if metric_name
@metrics[metric_name.to_sym] ||= []
@metrics[metric_name.to_sym] << Split::Experiment.new(key)
end
end
end
end
@metrics
end
def normalized_experiments
return nil if @experiments.nil?
experiment_config = {}
@experiments.keys.each do |name|
experiment_config[name.to_sym] = {}
end
@experiments.each do |experiment_name, settings|
alternatives = if (alts = value_for(settings, :alternatives))
normalize_alternatives(alts)
end
experiment_data = {
alternatives: alternatives,
goals: value_for(settings, :goals),
metadata: value_for(settings, :metadata),
algorithm: value_for(settings, :algorithm),
resettable: value_for(settings, :resettable)
}
experiment_data.each do |name, value|
experiment_config[experiment_name.to_sym][name] = value if value != nil
end
end
experiment_config
end
def normalize_alternatives(alternatives)
given_probability, num_with_probability = alternatives.inject([0, 0]) do |a, v|
p, n = a
if percent = value_for(v, :percent)
[p + percent, n + 1]
else
a
end
end
num_without_probability = alternatives.length - num_with_probability
unassigned_probability = ((100.0 - given_probability) / num_without_probability / 100.0)
if num_with_probability.nonzero?
alternatives = alternatives.map do |v|
if (name = value_for(v, :name)) && (percent = value_for(v, :percent))
{ name => percent / 100.0 }
elsif name = value_for(v, :name)
{ name => unassigned_probability }
else
{ v => unassigned_probability }
end
end
[alternatives.shift, alternatives]
else
alternatives = alternatives.dup
[alternatives.shift, alternatives]
end
end
def robot_regex
@robot_regex ||= /\b(?:#{escaped_bots.join('|')})\b|\A\W*\z/i
end
def initialize
@ignore_ip_addresses = []
@ignore_filter = proc { |request| is_robot? || is_ignored_ip_address? }
@db_failover = false
@db_failover_on_db_error = proc { |error| } # e.g. use Rails logger here
@on_experiment_reset = proc { |experiment| }
@on_experiment_delete = proc { |experiment| }
@on_before_experiment_reset = proc { |experiment| }
@on_before_experiment_delete = proc { |experiment| }
@on_experiment_winner_choose = proc { |experiment| }
@db_failover_allow_parameter_override = false
@allow_multiple_experiments = false
@enabled = true
@experiments = {}
@persistence = Split::Persistence::SessionAdapter
@persistence_cookie_length = 31536000 # One year from now
@persistence_cookie_domain = nil
@algorithm = Split::Algorithms::WeightedSample
@include_rails_helper = true
@beta_probability_simulations = 10000
@winning_alternative_recalculation_interval = 60 * 60 * 24 # 1 day
@redis = ENV.fetch(ENV.fetch("REDIS_PROVIDER", "REDIS_URL"), "redis://localhost:6379")
@dashboard_pagination_default_per_page = 10
end
private
def value_for(hash, key)
if hash.kind_of?(Hash)
hash.has_key?(key.to_s) ? hash[key.to_s] : hash[key.to_sym]
end
end
def escaped_bots
bots.map { |key, _| Regexp.escape(key) }
end
end
end
<MSG> Added another bot.
<DFF> @@ -26,11 +26,12 @@ module Split
'AdsBot-Google' => 'Google Adwords',
'Baidu' => 'Chinese search engine',
'Baiduspider' => 'Chinese search engine',
+ 'bingbot' => 'Microsoft bing bot',
'Butterfly' => 'Topsy Labs',
'Gigabot' => 'Gigabot spider',
'Googlebot' => 'Google spider',
+ 'MJ12bot' => 'Majestic-12 spider',
'msnbot' => 'Microsoft bot',
- 'bingbot' => 'Microsoft bing bot',
'rogerbot' => 'SeoMoz spider',
'PaperLiBot' => 'PaperLi is another content curation service',
'Slurp' => 'Yahoo spider',
| 2 | Added another bot. | 1 | .rb | rb | mit | splitrb/split |
10071924 | <NME> configuration.rb
<BEF> # frozen_string_literal: true
module Split
class Configuration
attr_accessor :ignore_ip_addresses
attr_accessor :ignore_filter
attr_accessor :db_failover
attr_accessor :db_failover_on_db_error
attr_accessor :db_failover_allow_parameter_override
attr_accessor :allow_multiple_experiments
attr_accessor :enabled
attr_accessor :persistence
attr_accessor :persistence_cookie_length
attr_accessor :persistence_cookie_domain
attr_accessor :algorithm
attr_accessor :store_override
attr_accessor :start_manually
attr_accessor :reset_manually
attr_accessor :on_trial
attr_accessor :on_trial_choose
attr_accessor :on_trial_complete
attr_accessor :on_experiment_reset
attr_accessor :on_experiment_delete
attr_accessor :on_before_experiment_reset
attr_accessor :on_experiment_winner_choose
'AdsBot-Google' => 'Google Adwords',
'Baidu' => 'Chinese search engine',
'Baiduspider' => 'Chinese search engine',
'Butterfly' => 'Topsy Labs',
'Gigabot' => 'Gigabot spider',
'Googlebot' => 'Google spider',
'msnbot' => 'Microsoft bot',
'bingbot' => 'Microsoft bing bot',
'rogerbot' => 'SeoMoz spider',
'PaperLiBot' => 'PaperLi is another content curation service',
'Slurp' => 'Yahoo spider',
def bots
@bots ||= {
# Indexers
"AdsBot-Google" => "Google Adwords",
"Baidu" => "Chinese search engine",
"Baiduspider" => "Chinese search engine",
"bingbot" => "Microsoft bing bot",
"Butterfly" => "Topsy Labs",
"Gigabot" => "Gigabot spider",
"Googlebot" => "Google spider",
"MJ12bot" => "Majestic-12 spider",
"msnbot" => "Microsoft bot",
"rogerbot" => "SeoMoz spider",
"PaperLiBot" => "PaperLi is another content curation service",
"Slurp" => "Yahoo spider",
"Sogou" => "Chinese search engine",
"spider" => "generic web spider",
"UnwindFetchor" => "Gnip crawler",
"WordPress" => "WordPress spider",
"YandexAccessibilityBot" => "Yandex accessibility spider",
"YandexBot" => "Yandex spider",
"YandexMobileBot" => "Yandex mobile spider",
"ZIBB" => "ZIBB spider",
# HTTP libraries
"Apache-HttpClient" => "Java http library",
"AppEngine-Google" => "Google App Engine",
"curl" => "curl unix CLI http client",
"ColdFusion" => "ColdFusion http library",
"EventMachine HttpClient" => "Ruby http library",
"Go http package" => "Go http library",
"Go-http-client" => "Go http library",
"Java" => "Generic Java http library",
"libwww-perl" => "Perl client-server library loved by script kids",
"lwp-trivial" => "Another Perl library loved by script kids",
"Python-urllib" => "Python http library",
"PycURL" => "Python http library",
"Test Certificate Info" => "C http library?",
"Typhoeus" => "Ruby http library",
"Wget" => "wget unix CLI http client",
# URL expanders / previewers
"awe.sm" => "Awe.sm URL expander",
"bitlybot" => "bit.ly bot",
"[email protected]" => "Linkfluence bot",
"facebookexternalhit" => "facebook bot",
"Facebot" => "Facebook crawler",
"Feedfetcher-Google" => "Google Feedfetcher",
"https://developers.google.com/+/web/snippet" => "Google+ Snippet Fetcher",
"LinkedInBot" => "LinkedIn bot",
"LongURL" => "URL expander service",
"NING" => "NING - Yet Another Twitter Swarmer",
"Pinterestbot" => "Pinterest Bot",
"redditbot" => "Reddit Bot",
"ShortLinkTranslate" => "Link shortener",
"Slackbot" => "Slackbot link expander",
"TweetmemeBot" => "TweetMeMe Crawler",
"Twitterbot" => "Twitter URL expander",
"UnwindFetch" => "Gnip URL expander",
"vkShare" => "VKontake Sharer",
# Uptime monitoring
"check_http" => "Nagios monitor",
"GoogleStackdriverMonitoring" => "Google Cloud monitor",
"NewRelicPinger" => "NewRelic monitor",
"Panopta" => "Monitoring service",
"Pingdom" => "Pingdom monitoring",
"SiteUptime" => "Site monitoring services",
"UptimeRobot" => "Monitoring service",
# ???
"DigitalPersona Fingerprint Software" => "HP Fingerprint scanner",
"ShowyouBot" => "Showyou iOS app spider",
"ZyBorg" => "Zyborg? Hmmm....",
"ELB-HealthChecker" => "ELB Health Check"
}
end
def experiments=(experiments)
raise InvalidExperimentsFormatError.new("Experiments must be a Hash") unless experiments.respond_to?(:keys)
@experiments = experiments
end
def disabled?
!enabled
end
def experiment_for(name)
if normalized_experiments
# TODO symbols
normalized_experiments[name.to_sym]
end
end
def metrics
return @metrics if defined?(@metrics)
@metrics = {}
if self.experiments
self.experiments.each do |key, value|
metrics = value_for(value, :metric) rescue nil
Array(metrics).each do |metric_name|
if metric_name
@metrics[metric_name.to_sym] ||= []
@metrics[metric_name.to_sym] << Split::Experiment.new(key)
end
end
end
end
@metrics
end
def normalized_experiments
return nil if @experiments.nil?
experiment_config = {}
@experiments.keys.each do |name|
experiment_config[name.to_sym] = {}
end
@experiments.each do |experiment_name, settings|
alternatives = if (alts = value_for(settings, :alternatives))
normalize_alternatives(alts)
end
experiment_data = {
alternatives: alternatives,
goals: value_for(settings, :goals),
metadata: value_for(settings, :metadata),
algorithm: value_for(settings, :algorithm),
resettable: value_for(settings, :resettable)
}
experiment_data.each do |name, value|
experiment_config[experiment_name.to_sym][name] = value if value != nil
end
end
experiment_config
end
def normalize_alternatives(alternatives)
given_probability, num_with_probability = alternatives.inject([0, 0]) do |a, v|
p, n = a
if percent = value_for(v, :percent)
[p + percent, n + 1]
else
a
end
end
num_without_probability = alternatives.length - num_with_probability
unassigned_probability = ((100.0 - given_probability) / num_without_probability / 100.0)
if num_with_probability.nonzero?
alternatives = alternatives.map do |v|
if (name = value_for(v, :name)) && (percent = value_for(v, :percent))
{ name => percent / 100.0 }
elsif name = value_for(v, :name)
{ name => unassigned_probability }
else
{ v => unassigned_probability }
end
end
[alternatives.shift, alternatives]
else
alternatives = alternatives.dup
[alternatives.shift, alternatives]
end
end
def robot_regex
@robot_regex ||= /\b(?:#{escaped_bots.join('|')})\b|\A\W*\z/i
end
def initialize
@ignore_ip_addresses = []
@ignore_filter = proc { |request| is_robot? || is_ignored_ip_address? }
@db_failover = false
@db_failover_on_db_error = proc { |error| } # e.g. use Rails logger here
@on_experiment_reset = proc { |experiment| }
@on_experiment_delete = proc { |experiment| }
@on_before_experiment_reset = proc { |experiment| }
@on_before_experiment_delete = proc { |experiment| }
@on_experiment_winner_choose = proc { |experiment| }
@db_failover_allow_parameter_override = false
@allow_multiple_experiments = false
@enabled = true
@experiments = {}
@persistence = Split::Persistence::SessionAdapter
@persistence_cookie_length = 31536000 # One year from now
@persistence_cookie_domain = nil
@algorithm = Split::Algorithms::WeightedSample
@include_rails_helper = true
@beta_probability_simulations = 10000
@winning_alternative_recalculation_interval = 60 * 60 * 24 # 1 day
@redis = ENV.fetch(ENV.fetch("REDIS_PROVIDER", "REDIS_URL"), "redis://localhost:6379")
@dashboard_pagination_default_per_page = 10
end
private
def value_for(hash, key)
if hash.kind_of?(Hash)
hash.has_key?(key.to_s) ? hash[key.to_s] : hash[key.to_sym]
end
end
def escaped_bots
bots.map { |key, _| Regexp.escape(key) }
end
end
end
<MSG> Added another bot.
<DFF> @@ -26,11 +26,12 @@ module Split
'AdsBot-Google' => 'Google Adwords',
'Baidu' => 'Chinese search engine',
'Baiduspider' => 'Chinese search engine',
+ 'bingbot' => 'Microsoft bing bot',
'Butterfly' => 'Topsy Labs',
'Gigabot' => 'Gigabot spider',
'Googlebot' => 'Google spider',
+ 'MJ12bot' => 'Majestic-12 spider',
'msnbot' => 'Microsoft bot',
- 'bingbot' => 'Microsoft bing bot',
'rogerbot' => 'SeoMoz spider',
'PaperLiBot' => 'PaperLi is another content curation service',
'Slurp' => 'Yahoo spider',
| 2 | Added another bot. | 1 | .rb | rb | mit | splitrb/split |
10071925 | <NME> config.ts
<BEF> import { Abbreviation } from '@emmetio/abbreviation';
import markupSnippets from '../snippets/html.json';
import stylesheetSnippets from '../snippets/css.json';
import xslSnippets from '../snippets/xsl.json';
import pugSnippets from '../snippets/pug.json';
import variables from '../snippets/variables.json';
import { CSSSnippet } from './stylesheet/snippets';
export type SyntaxType = 'markup' | 'stylesheet';
export type FieldOutput = (index: number, placeholder: string, offset: number, line: number, column: number) => string;
export type TextOutput = (text: string, offset: number, line: number, column: number) => string;
export type StringCase = '' | 'lower' | 'upper';
export interface SnippetsMap {
[name: string]: string;
}
export interface AbbreviationContext {
name: string;
attributes?: { [name: string]: string | null };
}
/**
* Raw config which contains per-syntax options. `markup` and `syntax` keys are
* reserved for global settings for all markup and stylesheet syntaxes
*/
export interface GlobalConfig {
[syntax: string]: Partial<BaseConfig>;
}
export interface BaseConfig {
/* Type of abbreviation context, default is `markup` */
type: SyntaxType;
/** Options for abbreviation output */
options: Partial<Options>;
/** Substitutions for variable names */
variables: SnippetsMap;
/** Abbreviation name to snippets mapping */
snippets: SnippetsMap;
}
interface ResolvedConfig extends BaseConfig {
/** Host syntax */
syntax: string;
/**
* Context of abbreviation. For markup abbreviation, it contains parent tag
* name with attributes, for stylesheet abbreviation it contains property name
* if abbreviation is expanded as value
*/
context?: AbbreviationContext;
/** Text to wrap with abbreviation */
text?: string | string[];
/** Max amount of repeated elements (fool proof) */
maxRepeat?: number;
/**
* Object for storing internal cache data to be shared across Emmet methods
* invocation. If provided, Emmet will store compute-intensive data in this
* object and will re-use it during editor session.
* Every time user settings are changed, you should empty cache by passing
* new object.
*/
cache?: Cache;
}
export type Config = ResolvedConfig & { options: Options };
export type UserConfig = Partial<ResolvedConfig>;
export interface Cache {
stylesheetSnippets?: CSSSnippet[];
markupSnippets?: { [name: string]: Abbreviation | null };
}
export interface Options {
/////////////////////
// Generic options //
/////////////////////
/** A list of inline-level elements */
inlineElements: string[];
////////////////////
// Output options //
////////////////////
/** A string for one level indent */
'output.indent': string;
/**
* A string for base indent, e.g. context indentation which will be added
* for every generated line
*/
'output.baseIndent': string;
/** A string to use as a new line */
'output.newline': string;
/** Tag case: lower, upper or '' (keep as-is) */
'output.tagCase': StringCase;
/** Attribute name case: lower, upper or '' (keep as-is) */
'output.attributeCase': StringCase;
/** Attribute value quotes: 'single' or 'double' */
'output.attributeQuotes': 'single' | 'double';
/** Enable output formatting (indentation and line breaks) */
'output.format': boolean;
/** When enabled, automatically adds inner line breaks for leaf (e.g. without children) nodes */
'output.formatLeafNode': boolean;
/** A list of tag names that should not get inner indentation */
'output.formatSkip': string[];
/** A list of tag names that should *always* get inner indentation. */
'output.formatForce': string[];
/**
* How many inline sibling elements should force line break for each tag.
* Set to `0` to output all inline elements without formatting.
* Set to `1` to output all inline elements with formatting (same as block-level).
*/
'output.inlineBreak': number;
/**
* Produce compact notation of boolean attributes: attributes which doesn’t have value.
* With this option enabled, outputs `<div contenteditable>` instead of
* `<div contenteditable="contenteditable">`
*/
'output.compactBoolean': boolean;
/** A list of boolean attributes */
'output.booleanAttributes': string[];
/** Reverses attribute merging directions when resolving snippets */
'output.reverseAttributes': boolean;
/** Style of self-closing tags: html (`<br>`), xml (`<br/>`) or xhtml (`<br />`) */
'output.selfClosingStyle': 'html' | 'xml' | 'xhtml';
/**
* A function that takes field index and optional placeholder and returns
* a string field (tabstop) for host editor. For example, a TextMate-style
* field is `$index` or `${index:placeholder}`
* @param index Field index
* @param placeholder Field placeholder (default value), if any
* @param offset Current character offset from the beginning of generated content
* @param line Current line of generated output
* @param column Current column in line
*/
'output.field': FieldOutput;
/**
* A function for processing text chunk passed to `OutputStream`.
* May be used by editor for escaping characters, if necessary
*/
'output.text': TextOutput;
////////////////////
// Markup options //
////////////////////
/**
* Automatically update value of <a> element's href attribute
* if inserting URL or email
*/
'markup.href': boolean;
/**
* Attribute name mapping. Can be used to change attribute names for output.
* For example, `class` -> `className` in JSX. If a key ends with `*`, this
* value will be used for multi-attributes: currentry, it’s a `class` and `id`
* since `multiple` marker is added for shorthand attributes only.
* Example: `{ "class*": "styleName" }`
*/
'markup.attributes'?: Record<string, string>;
/**
* Prefixes for attribute values.
* If specified, a value is treated as prefix for object notation and
* automatically converts attribute value into expression if `jsx` is enabled.
* Same as in `markup.attributes` option, a `*` can be used.
*/
'markup.valuePrefix'?: Record<string, string>;
////////////////////////////////
// Element commenting options //
////////////////////////////////
/**
* Enable/disable element commenting: generate comments before open and/or
* after close tag
*/
'comment.enabled': boolean;
/**
* Attributes that should trigger node commenting on specific node,
* if commenting is enabled
*/
'comment.trigger': string[];
/**
* Template string for comment to be placed *before* opening tag
*/
'comment.before': string;
/**
* Template string for comment to be placed *after* closing tag.
* Example: `\n<!-- /[#ID][.CLASS] -->`
*/
'comment.after': string;
/////////////////
// BEM options //
/////////////////
/** Enable/disable BEM addon */
'bem.enabled': boolean;
/** A string for separating elements in output class */
'bem.element': string;
/** A string for separating modifiers in output class */
'bem.modifier': string;
/////////////////
// JSX options //
/////////////////
/** Enable/disable JSX addon */
'jsx.enabled': boolean;
////////////////////////
// Stylesheet options //
////////////////////////
/** List of globally available keywords for properties */
'stylesheet.keywords': string[];
/**
* List of unitless properties, e.g. properties where numeric values without
* explicit unit will be outputted as is, without default value
*/
'stylesheet.unitless': string[];
/** Use short hex notation where possible, e.g. `#000` instead of `#000000` */
'stylesheet.shortHex': boolean;
/** A string between property name and value */
'stylesheet.between': string;
/** A string after property value */
'stylesheet.after': string;
/** A unit suffix to output by default after integer values, 'px' by default */
'stylesheet.intUnit': string;
/** A unit suffix to output by default after float values, 'em' by default */
'stylesheet.floatUnit': string;
/**
* Aliases for custom units in abbreviation. For example, `r: 'rem'` will
* output `10rem` for abbreviation `10r`
*/
'stylesheet.unitAliases': SnippetsMap;
/** Output abbreviation as JSON object properties (for CSS-in-JS syntaxes) */
'stylesheet.json': boolean;
/** Use double quotes for JSON values */
'stylesheet.jsonDoubleQuotes': boolean;
/**
* A float number between 0 and 1 to pick fuzzy-matched abbreviations.
* Lower value will pick more abbreviations (and less accurate)
*/
'stylesheet.fuzzySearchMinScore': number;
}
/**
* Default syntaxes for abbreviation types
*/
export const defaultSyntaxes: { [name in SyntaxType]: string } = {
markup: 'html',
stylesheet: 'css'
};
/**
* List of all known syntaxes
*/
export const syntaxes = {
markup: ['html', 'xml', 'xsl', 'jsx', 'js', 'pug', 'slim', 'haml', 'vue', 'svelte'],
stylesheet: ['css', 'sass', 'scss', 'less', 'sss', 'stylus']
};
export const defaultOptions: Options = {
'inlineElements': [
'a', 'abbr', 'acronym', 'applet', 'b', 'basefont', 'bdo',
'big', 'br', 'button', 'cite', 'code', 'del', 'dfn', 'em', 'font', 'i',
'iframe', 'img', 'input', 'ins', 'kbd', 'label', 'map', 'object', 'q',
's', 'samp', 'select', 'small', 'span', 'strike', 'strong', 'sub', 'sup',
'textarea', 'tt', 'u', 'var'
],
'output.indent': '\t',
'output.baseIndent': '',
'output.newline': '\n',
'output.tagCase': '',
'output.attributeCase': '',
'output.attributeQuotes': 'double',
'output.format': true,
'output.formatLeafNode': false,
'output.formatSkip': ['html'],
'output.formatForce': ['body'],
'output.inlineBreak': 3,
'output.compactBoolean': false,
'output.booleanAttributes': [
'contenteditable', 'seamless', 'async', 'autofocus',
'autoplay', 'checked', 'controls', 'defer', 'disabled', 'formnovalidate',
'hidden', 'ismap', 'loop', 'multiple', 'muted', 'novalidate', 'readonly',
'required', 'reversed', 'selected', 'typemustmatch'
],
'output.reverseAttributes': false,
'output.selfClosingStyle': 'html',
'output.field': (index, placeholder) => placeholder,
'output.text': text => text,
'markup.href': true,
'comment.enabled': false,
'comment.trigger': ['id', 'class'],
'comment.before': '',
'comment.after': '\n<!-- /[#ID][.CLASS] -->',
'bem.enabled': false,
'bem.element': '__',
'bem.modifier': '_',
'jsx.enabled': false,
'stylesheet.keywords': ['auto', 'inherit', 'unset', 'none'],
'stylesheet.unitless': ['z-index', 'line-height', 'opacity', 'font-weight', 'zoom', 'flex', 'flex-grow', 'flex-shrink'],
'stylesheet.shortHex': true,
'stylesheet.between': ': ',
'stylesheet.after': ';',
'stylesheet.intUnit': 'px',
'stylesheet.floatUnit': 'em',
'stylesheet.unitAliases': { e: 'em', p: '%', x: 'ex', r: 'rem' },
'stylesheet.json': false,
'stylesheet.jsonDoubleQuotes': false,
'stylesheet.fuzzySearchMinScore': 0
};
export const defaultConfig: Config = {
type: 'markup',
syntax: 'html',
variables,
snippets: {},
options: defaultOptions
};
/**
* Default per-syntax config
*/
export const syntaxConfig: GlobalConfig = {
markup: {
snippets: parseSnippets(markupSnippets),
},
xhtml: {
options: {
'output.selfClosingStyle': 'xhtml'
}
},
xml: {
options: {
'output.selfClosingStyle': 'xml'
}
},
xsl: {
snippets: parseSnippets(xslSnippets),
options: {
'output.selfClosingStyle': 'xml'
}
},
jsx: {
options: {
'jsx.enabled': true,
'markup.attributes': {
'class': 'className',
'class*': 'styleName',
'for': 'htmlFor'
},
'markup.valuePrefix': {
'class*': 'styles'
}
const syntaxOverride = globals[syntax];
return {
...defaultConfig[key],
...(typeDefaults && typeDefaults[key]),
...(syntaxDefaults && syntaxDefaults[key]),
...(typeOverride && typeOverride[key]),
...(syntaxOverride && syntaxOverride[key]),
...config[key]
};
}
'jsx.enabled': true
}
},
pug: {
snippets: parseSnippets(pugSnippets)
},
stylesheet: {
snippets: parseSnippets(stylesheetSnippets)
},
sass: {
options: {
'stylesheet.after': ''
}
},
stylus: {
options: {
'stylesheet.between': ' ',
'stylesheet.after': '',
}
}
};
/**
* Parses raw snippets definitions with possibly multiple keys into a plan
* snippet map
*/
export function parseSnippets(snippets: SnippetsMap): SnippetsMap {
const result: SnippetsMap = {};
Object.keys(snippets).forEach(k => {
for (const name of k.split('|')) {
result[name] = snippets[k];
}
});
return result;
}
export default function resolveConfig(config: UserConfig = {}, globals: GlobalConfig = {}): Config {
const type: SyntaxType = config.type || 'markup';
const syntax: string = config.syntax || defaultSyntaxes[type];
return {
...defaultConfig,
...config,
type,
syntax,
variables: mergedData(type, syntax, 'variables', config, globals),
snippets: mergedData(type, syntax, 'snippets', config, globals),
options: mergedData(type, syntax, 'options', config, globals)
};
}
function mergedData<K extends keyof BaseConfig>(type: SyntaxType, syntax: string, key: K, config: UserConfig, globals: GlobalConfig = {}): Config[K] {
const typeDefaults = syntaxConfig[type];
const typeOverride = globals[type];
const syntaxDefaults = syntaxConfig[syntax];
const syntaxOverride = globals[syntax];
return {
...(defaultConfig[key] as object),
...(typeDefaults && typeDefaults[key] as object),
...(syntaxDefaults && syntaxDefaults[key] as object),
...(typeOverride && typeOverride[key] as object),
...(syntaxOverride && syntaxOverride[key] as object),
...(config[key] as object)
} as Config[K];
}
<MSG> Updated deps
<DFF> @@ -401,11 +401,11 @@ function mergedData<K extends keyof BaseConfig>(type: SyntaxType, syntax: string
const syntaxOverride = globals[syntax];
return {
- ...defaultConfig[key],
- ...(typeDefaults && typeDefaults[key]),
- ...(syntaxDefaults && syntaxDefaults[key]),
- ...(typeOverride && typeOverride[key]),
- ...(syntaxOverride && syntaxOverride[key]),
- ...config[key]
- };
+ ...(defaultConfig[key] as object),
+ ...(typeDefaults && typeDefaults[key] as object),
+ ...(syntaxDefaults && syntaxDefaults[key] as object),
+ ...(typeOverride && typeOverride[key] as object),
+ ...(syntaxOverride && syntaxOverride[key] as object),
+ ...(config[key] as object)
+ } as Config[K];
}
| 7 | Updated deps | 7 | .ts | ts | mit | emmetio/emmet |
10071926 | <NME> config.ts
<BEF> import { Abbreviation } from '@emmetio/abbreviation';
import markupSnippets from '../snippets/html.json';
import stylesheetSnippets from '../snippets/css.json';
import xslSnippets from '../snippets/xsl.json';
import pugSnippets from '../snippets/pug.json';
import variables from '../snippets/variables.json';
import { CSSSnippet } from './stylesheet/snippets';
export type SyntaxType = 'markup' | 'stylesheet';
export type FieldOutput = (index: number, placeholder: string, offset: number, line: number, column: number) => string;
export type TextOutput = (text: string, offset: number, line: number, column: number) => string;
export type StringCase = '' | 'lower' | 'upper';
export interface SnippetsMap {
[name: string]: string;
}
export interface AbbreviationContext {
name: string;
attributes?: { [name: string]: string | null };
}
/**
* Raw config which contains per-syntax options. `markup` and `syntax` keys are
* reserved for global settings for all markup and stylesheet syntaxes
*/
export interface GlobalConfig {
[syntax: string]: Partial<BaseConfig>;
}
export interface BaseConfig {
/* Type of abbreviation context, default is `markup` */
type: SyntaxType;
/** Options for abbreviation output */
options: Partial<Options>;
/** Substitutions for variable names */
variables: SnippetsMap;
/** Abbreviation name to snippets mapping */
snippets: SnippetsMap;
}
interface ResolvedConfig extends BaseConfig {
/** Host syntax */
syntax: string;
/**
* Context of abbreviation. For markup abbreviation, it contains parent tag
* name with attributes, for stylesheet abbreviation it contains property name
* if abbreviation is expanded as value
*/
context?: AbbreviationContext;
/** Text to wrap with abbreviation */
text?: string | string[];
/** Max amount of repeated elements (fool proof) */
maxRepeat?: number;
/**
* Object for storing internal cache data to be shared across Emmet methods
* invocation. If provided, Emmet will store compute-intensive data in this
* object and will re-use it during editor session.
* Every time user settings are changed, you should empty cache by passing
* new object.
*/
cache?: Cache;
}
export type Config = ResolvedConfig & { options: Options };
export type UserConfig = Partial<ResolvedConfig>;
export interface Cache {
stylesheetSnippets?: CSSSnippet[];
markupSnippets?: { [name: string]: Abbreviation | null };
}
export interface Options {
/////////////////////
// Generic options //
/////////////////////
/** A list of inline-level elements */
inlineElements: string[];
////////////////////
// Output options //
////////////////////
/** A string for one level indent */
'output.indent': string;
/**
* A string for base indent, e.g. context indentation which will be added
* for every generated line
*/
'output.baseIndent': string;
/** A string to use as a new line */
'output.newline': string;
/** Tag case: lower, upper or '' (keep as-is) */
'output.tagCase': StringCase;
/** Attribute name case: lower, upper or '' (keep as-is) */
'output.attributeCase': StringCase;
/** Attribute value quotes: 'single' or 'double' */
'output.attributeQuotes': 'single' | 'double';
/** Enable output formatting (indentation and line breaks) */
'output.format': boolean;
/** When enabled, automatically adds inner line breaks for leaf (e.g. without children) nodes */
'output.formatLeafNode': boolean;
/** A list of tag names that should not get inner indentation */
'output.formatSkip': string[];
/** A list of tag names that should *always* get inner indentation. */
'output.formatForce': string[];
/**
* How many inline sibling elements should force line break for each tag.
* Set to `0` to output all inline elements without formatting.
* Set to `1` to output all inline elements with formatting (same as block-level).
*/
'output.inlineBreak': number;
/**
* Produce compact notation of boolean attributes: attributes which doesn’t have value.
* With this option enabled, outputs `<div contenteditable>` instead of
* `<div contenteditable="contenteditable">`
*/
'output.compactBoolean': boolean;
/** A list of boolean attributes */
'output.booleanAttributes': string[];
/** Reverses attribute merging directions when resolving snippets */
'output.reverseAttributes': boolean;
/** Style of self-closing tags: html (`<br>`), xml (`<br/>`) or xhtml (`<br />`) */
'output.selfClosingStyle': 'html' | 'xml' | 'xhtml';
/**
* A function that takes field index and optional placeholder and returns
* a string field (tabstop) for host editor. For example, a TextMate-style
* field is `$index` or `${index:placeholder}`
* @param index Field index
* @param placeholder Field placeholder (default value), if any
* @param offset Current character offset from the beginning of generated content
* @param line Current line of generated output
* @param column Current column in line
*/
'output.field': FieldOutput;
/**
* A function for processing text chunk passed to `OutputStream`.
* May be used by editor for escaping characters, if necessary
*/
'output.text': TextOutput;
////////////////////
// Markup options //
////////////////////
/**
* Automatically update value of <a> element's href attribute
* if inserting URL or email
*/
'markup.href': boolean;
/**
* Attribute name mapping. Can be used to change attribute names for output.
* For example, `class` -> `className` in JSX. If a key ends with `*`, this
* value will be used for multi-attributes: currentry, it’s a `class` and `id`
* since `multiple` marker is added for shorthand attributes only.
* Example: `{ "class*": "styleName" }`
*/
'markup.attributes'?: Record<string, string>;
/**
* Prefixes for attribute values.
* If specified, a value is treated as prefix for object notation and
* automatically converts attribute value into expression if `jsx` is enabled.
* Same as in `markup.attributes` option, a `*` can be used.
*/
'markup.valuePrefix'?: Record<string, string>;
////////////////////////////////
// Element commenting options //
////////////////////////////////
/**
* Enable/disable element commenting: generate comments before open and/or
* after close tag
*/
'comment.enabled': boolean;
/**
* Attributes that should trigger node commenting on specific node,
* if commenting is enabled
*/
'comment.trigger': string[];
/**
* Template string for comment to be placed *before* opening tag
*/
'comment.before': string;
/**
* Template string for comment to be placed *after* closing tag.
* Example: `\n<!-- /[#ID][.CLASS] -->`
*/
'comment.after': string;
/////////////////
// BEM options //
/////////////////
/** Enable/disable BEM addon */
'bem.enabled': boolean;
/** A string for separating elements in output class */
'bem.element': string;
/** A string for separating modifiers in output class */
'bem.modifier': string;
/////////////////
// JSX options //
/////////////////
/** Enable/disable JSX addon */
'jsx.enabled': boolean;
////////////////////////
// Stylesheet options //
////////////////////////
/** List of globally available keywords for properties */
'stylesheet.keywords': string[];
/**
* List of unitless properties, e.g. properties where numeric values without
* explicit unit will be outputted as is, without default value
*/
'stylesheet.unitless': string[];
/** Use short hex notation where possible, e.g. `#000` instead of `#000000` */
'stylesheet.shortHex': boolean;
/** A string between property name and value */
'stylesheet.between': string;
/** A string after property value */
'stylesheet.after': string;
/** A unit suffix to output by default after integer values, 'px' by default */
'stylesheet.intUnit': string;
/** A unit suffix to output by default after float values, 'em' by default */
'stylesheet.floatUnit': string;
/**
* Aliases for custom units in abbreviation. For example, `r: 'rem'` will
* output `10rem` for abbreviation `10r`
*/
'stylesheet.unitAliases': SnippetsMap;
/** Output abbreviation as JSON object properties (for CSS-in-JS syntaxes) */
'stylesheet.json': boolean;
/** Use double quotes for JSON values */
'stylesheet.jsonDoubleQuotes': boolean;
/**
* A float number between 0 and 1 to pick fuzzy-matched abbreviations.
* Lower value will pick more abbreviations (and less accurate)
*/
'stylesheet.fuzzySearchMinScore': number;
}
/**
* Default syntaxes for abbreviation types
*/
export const defaultSyntaxes: { [name in SyntaxType]: string } = {
markup: 'html',
stylesheet: 'css'
};
/**
* List of all known syntaxes
*/
export const syntaxes = {
markup: ['html', 'xml', 'xsl', 'jsx', 'js', 'pug', 'slim', 'haml', 'vue', 'svelte'],
stylesheet: ['css', 'sass', 'scss', 'less', 'sss', 'stylus']
};
export const defaultOptions: Options = {
'inlineElements': [
'a', 'abbr', 'acronym', 'applet', 'b', 'basefont', 'bdo',
'big', 'br', 'button', 'cite', 'code', 'del', 'dfn', 'em', 'font', 'i',
'iframe', 'img', 'input', 'ins', 'kbd', 'label', 'map', 'object', 'q',
's', 'samp', 'select', 'small', 'span', 'strike', 'strong', 'sub', 'sup',
'textarea', 'tt', 'u', 'var'
],
'output.indent': '\t',
'output.baseIndent': '',
'output.newline': '\n',
'output.tagCase': '',
'output.attributeCase': '',
'output.attributeQuotes': 'double',
'output.format': true,
'output.formatLeafNode': false,
'output.formatSkip': ['html'],
'output.formatForce': ['body'],
'output.inlineBreak': 3,
'output.compactBoolean': false,
'output.booleanAttributes': [
'contenteditable', 'seamless', 'async', 'autofocus',
'autoplay', 'checked', 'controls', 'defer', 'disabled', 'formnovalidate',
'hidden', 'ismap', 'loop', 'multiple', 'muted', 'novalidate', 'readonly',
'required', 'reversed', 'selected', 'typemustmatch'
],
'output.reverseAttributes': false,
'output.selfClosingStyle': 'html',
'output.field': (index, placeholder) => placeholder,
'output.text': text => text,
'markup.href': true,
'comment.enabled': false,
'comment.trigger': ['id', 'class'],
'comment.before': '',
'comment.after': '\n<!-- /[#ID][.CLASS] -->',
'bem.enabled': false,
'bem.element': '__',
'bem.modifier': '_',
'jsx.enabled': false,
'stylesheet.keywords': ['auto', 'inherit', 'unset', 'none'],
'stylesheet.unitless': ['z-index', 'line-height', 'opacity', 'font-weight', 'zoom', 'flex', 'flex-grow', 'flex-shrink'],
'stylesheet.shortHex': true,
'stylesheet.between': ': ',
'stylesheet.after': ';',
'stylesheet.intUnit': 'px',
'stylesheet.floatUnit': 'em',
'stylesheet.unitAliases': { e: 'em', p: '%', x: 'ex', r: 'rem' },
'stylesheet.json': false,
'stylesheet.jsonDoubleQuotes': false,
'stylesheet.fuzzySearchMinScore': 0
};
export const defaultConfig: Config = {
type: 'markup',
syntax: 'html',
variables,
snippets: {},
options: defaultOptions
};
/**
* Default per-syntax config
*/
export const syntaxConfig: GlobalConfig = {
markup: {
snippets: parseSnippets(markupSnippets),
},
xhtml: {
options: {
'output.selfClosingStyle': 'xhtml'
}
},
xml: {
options: {
'output.selfClosingStyle': 'xml'
}
},
xsl: {
snippets: parseSnippets(xslSnippets),
options: {
'output.selfClosingStyle': 'xml'
}
},
jsx: {
options: {
'jsx.enabled': true,
'markup.attributes': {
'class': 'className',
'class*': 'styleName',
'for': 'htmlFor'
},
'markup.valuePrefix': {
'class*': 'styles'
}
const syntaxOverride = globals[syntax];
return {
...defaultConfig[key],
...(typeDefaults && typeDefaults[key]),
...(syntaxDefaults && syntaxDefaults[key]),
...(typeOverride && typeOverride[key]),
...(syntaxOverride && syntaxOverride[key]),
...config[key]
};
}
'jsx.enabled': true
}
},
pug: {
snippets: parseSnippets(pugSnippets)
},
stylesheet: {
snippets: parseSnippets(stylesheetSnippets)
},
sass: {
options: {
'stylesheet.after': ''
}
},
stylus: {
options: {
'stylesheet.between': ' ',
'stylesheet.after': '',
}
}
};
/**
* Parses raw snippets definitions with possibly multiple keys into a plan
* snippet map
*/
export function parseSnippets(snippets: SnippetsMap): SnippetsMap {
const result: SnippetsMap = {};
Object.keys(snippets).forEach(k => {
for (const name of k.split('|')) {
result[name] = snippets[k];
}
});
return result;
}
export default function resolveConfig(config: UserConfig = {}, globals: GlobalConfig = {}): Config {
const type: SyntaxType = config.type || 'markup';
const syntax: string = config.syntax || defaultSyntaxes[type];
return {
...defaultConfig,
...config,
type,
syntax,
variables: mergedData(type, syntax, 'variables', config, globals),
snippets: mergedData(type, syntax, 'snippets', config, globals),
options: mergedData(type, syntax, 'options', config, globals)
};
}
function mergedData<K extends keyof BaseConfig>(type: SyntaxType, syntax: string, key: K, config: UserConfig, globals: GlobalConfig = {}): Config[K] {
const typeDefaults = syntaxConfig[type];
const typeOverride = globals[type];
const syntaxDefaults = syntaxConfig[syntax];
const syntaxOverride = globals[syntax];
return {
...(defaultConfig[key] as object),
...(typeDefaults && typeDefaults[key] as object),
...(syntaxDefaults && syntaxDefaults[key] as object),
...(typeOverride && typeOverride[key] as object),
...(syntaxOverride && syntaxOverride[key] as object),
...(config[key] as object)
} as Config[K];
}
<MSG> Updated deps
<DFF> @@ -401,11 +401,11 @@ function mergedData<K extends keyof BaseConfig>(type: SyntaxType, syntax: string
const syntaxOverride = globals[syntax];
return {
- ...defaultConfig[key],
- ...(typeDefaults && typeDefaults[key]),
- ...(syntaxDefaults && syntaxDefaults[key]),
- ...(typeOverride && typeOverride[key]),
- ...(syntaxOverride && syntaxOverride[key]),
- ...config[key]
- };
+ ...(defaultConfig[key] as object),
+ ...(typeDefaults && typeDefaults[key] as object),
+ ...(syntaxDefaults && syntaxDefaults[key] as object),
+ ...(typeOverride && typeOverride[key] as object),
+ ...(syntaxOverride && syntaxOverride[key] as object),
+ ...(config[key] as object)
+ } as Config[K];
}
| 7 | Updated deps | 7 | .ts | ts | mit | emmetio/emmet |
10071927 | <NME> user_spec.rb
<BEF> # frozen_string_literal: true
require "spec_helper"
require "split/experiment_catalog"
require "split/experiment"
require "split/user"
describe Split::User do
let(:user_keys) { { "link_color" => "blue" } }
let(:context) { double(session: { split: user_keys }) }
let(:experiment) { Split::Experiment.new("link_color") }
before(:each) do
@subject = described_class.new(context)
end
it "delegates methods correctly" do
expect(@subject["link_color"]).to eq(@subject.user["link_color"])
end
context "#cleanup_old_versions!" do
let(:experiment_version) { "#{experiment.name}:1" }
let(:second_experiment_version) { "#{experiment.name}_another:1" }
let(:third_experiment_version) { "variation_of_#{experiment.name}:1" }
let(:user_keys) do
{
experiment_version => "blue",
second_experiment_version => "red",
third_experiment_version => "yellow"
}
end
before(:each) { @subject.cleanup_old_versions!(experiment) }
it "removes key if old experiment is found" do
expect(@subject.keys).not_to include(experiment_version)
end
it "does not remove other keys" do
expect(@subject.keys).to include(second_experiment_version, third_experiment_version)
end
end
allow(experiment).to receive(:has_winner?).and_return(false)
@subject.cleanup_old_experiments!
expect(@subject.keys).to be_empty
end
end
end
context "with finished key" do
let(:user_keys) { { "link_color" => "blue", "link_color:finished" => true } }
it "does not remove finished key for experiment without a winner" do
allow(Split::ExperimentCatalog).to receive(:find).with("link_color").and_return(experiment)
allow(Split::ExperimentCatalog).to receive(:find).with("link_color:finished").and_return(nil)
allow(experiment).to receive(:start_time).and_return(Date.today)
allow(experiment).to receive(:has_winner?).and_return(false)
@subject.cleanup_old_experiments!
expect(@subject.keys).to include("link_color")
expect(@subject.keys).to include("link_color:finished")
end
end
context "when already cleaned up" do
before do
@subject.cleanup_old_experiments!
end
it "does not clean up again" do
expect(@subject).to_not receive(:keys_without_finished)
@subject.cleanup_old_experiments!
end
end
end
context "allows user to be loaded from adapter" do
it "loads user from adapter (RedisAdapter)" do
user = Split::Persistence::RedisAdapter.new(nil, 112233)
user["foo"] = "bar"
ab_user = Split::User.find(112233, :redis)
expect(ab_user["foo"]).to eql("bar")
end
it "returns nil if adapter does not implement a finder method" do
ab_user = Split::User.find(112233, :dual_adapter)
expect(ab_user).to be_nil
end
end
context "instantiated with custom adapter" do
let(:custom_adapter) { double(:persistence_adapter) }
before do
@subject = described_class.new(context, custom_adapter)
end
it "sets user to the custom adapter" do
expect(@subject.user).to eq(custom_adapter)
end
end
end
<MSG> FIX Negative numbers on non-finished
This fixes a major bug when negative non-finished numbers appear and simple random exception fired on dashboard.
The problem was with User#cleanup_old_experiments! method because it treats “experimen1:finished” key as a non-found experiment and just deletes it.
Related issues:
https://github.com/splitrb/split/issues/43
https://github.com/splitrb/split/issues/103
https://github.com/splitrb/split/issues/133
https://github.com/splitrb/split/issues/355
https://github.com/splitrb/split/issues/294
https://github.com/splitrb/split/issues/272
<DFF> @@ -44,6 +44,20 @@ describe Split::User do
allow(experiment).to receive(:has_winner?).and_return(false)
@subject.cleanup_old_experiments!
expect(@subject.keys).to be_empty
- end
+ end
+
+ context 'with finished key' do
+ let(:user_keys) { { 'link_color' => 'blue', 'link_color:finished' => true } }
+
+ it 'does not remove finished key for experiment without a winner' do
+ allow(Split::ExperimentCatalog).to receive(:find).with('link_color').and_return(experiment)
+ allow(Split::ExperimentCatalog).to receive(:find).with('link_color:finished').and_return(nil)
+ allow(experiment).to receive(:start_time).and_return(Date.today)
+ allow(experiment).to receive(:has_winner?).and_return(false)
+ @subject.cleanup_old_experiments!
+ expect(@subject.keys).to include("link_color")
+ expect(@subject.keys).to include("link_color:finished")
+ end
+ end
end
-end
\ No newline at end of file
+end
| 16 | FIX Negative numbers on non-finished | 2 | .rb | rb | mit | splitrb/split |
10071928 | <NME> user_spec.rb
<BEF> # frozen_string_literal: true
require "spec_helper"
require "split/experiment_catalog"
require "split/experiment"
require "split/user"
describe Split::User do
let(:user_keys) { { "link_color" => "blue" } }
let(:context) { double(session: { split: user_keys }) }
let(:experiment) { Split::Experiment.new("link_color") }
before(:each) do
@subject = described_class.new(context)
end
it "delegates methods correctly" do
expect(@subject["link_color"]).to eq(@subject.user["link_color"])
end
context "#cleanup_old_versions!" do
let(:experiment_version) { "#{experiment.name}:1" }
let(:second_experiment_version) { "#{experiment.name}_another:1" }
let(:third_experiment_version) { "variation_of_#{experiment.name}:1" }
let(:user_keys) do
{
experiment_version => "blue",
second_experiment_version => "red",
third_experiment_version => "yellow"
}
end
before(:each) { @subject.cleanup_old_versions!(experiment) }
it "removes key if old experiment is found" do
expect(@subject.keys).not_to include(experiment_version)
end
it "does not remove other keys" do
expect(@subject.keys).to include(second_experiment_version, third_experiment_version)
end
end
allow(experiment).to receive(:has_winner?).and_return(false)
@subject.cleanup_old_experiments!
expect(@subject.keys).to be_empty
end
end
end
context "with finished key" do
let(:user_keys) { { "link_color" => "blue", "link_color:finished" => true } }
it "does not remove finished key for experiment without a winner" do
allow(Split::ExperimentCatalog).to receive(:find).with("link_color").and_return(experiment)
allow(Split::ExperimentCatalog).to receive(:find).with("link_color:finished").and_return(nil)
allow(experiment).to receive(:start_time).and_return(Date.today)
allow(experiment).to receive(:has_winner?).and_return(false)
@subject.cleanup_old_experiments!
expect(@subject.keys).to include("link_color")
expect(@subject.keys).to include("link_color:finished")
end
end
context "when already cleaned up" do
before do
@subject.cleanup_old_experiments!
end
it "does not clean up again" do
expect(@subject).to_not receive(:keys_without_finished)
@subject.cleanup_old_experiments!
end
end
end
context "allows user to be loaded from adapter" do
it "loads user from adapter (RedisAdapter)" do
user = Split::Persistence::RedisAdapter.new(nil, 112233)
user["foo"] = "bar"
ab_user = Split::User.find(112233, :redis)
expect(ab_user["foo"]).to eql("bar")
end
it "returns nil if adapter does not implement a finder method" do
ab_user = Split::User.find(112233, :dual_adapter)
expect(ab_user).to be_nil
end
end
context "instantiated with custom adapter" do
let(:custom_adapter) { double(:persistence_adapter) }
before do
@subject = described_class.new(context, custom_adapter)
end
it "sets user to the custom adapter" do
expect(@subject.user).to eq(custom_adapter)
end
end
end
<MSG> FIX Negative numbers on non-finished
This fixes a major bug when negative non-finished numbers appear and simple random exception fired on dashboard.
The problem was with User#cleanup_old_experiments! method because it treats “experimen1:finished” key as a non-found experiment and just deletes it.
Related issues:
https://github.com/splitrb/split/issues/43
https://github.com/splitrb/split/issues/103
https://github.com/splitrb/split/issues/133
https://github.com/splitrb/split/issues/355
https://github.com/splitrb/split/issues/294
https://github.com/splitrb/split/issues/272
<DFF> @@ -44,6 +44,20 @@ describe Split::User do
allow(experiment).to receive(:has_winner?).and_return(false)
@subject.cleanup_old_experiments!
expect(@subject.keys).to be_empty
- end
+ end
+
+ context 'with finished key' do
+ let(:user_keys) { { 'link_color' => 'blue', 'link_color:finished' => true } }
+
+ it 'does not remove finished key for experiment without a winner' do
+ allow(Split::ExperimentCatalog).to receive(:find).with('link_color').and_return(experiment)
+ allow(Split::ExperimentCatalog).to receive(:find).with('link_color:finished').and_return(nil)
+ allow(experiment).to receive(:start_time).and_return(Date.today)
+ allow(experiment).to receive(:has_winner?).and_return(false)
+ @subject.cleanup_old_experiments!
+ expect(@subject.keys).to include("link_color")
+ expect(@subject.keys).to include("link_color:finished")
+ end
+ end
end
-end
\ No newline at end of file
+end
| 16 | FIX Negative numbers on non-finished | 2 | .rb | rb | mit | splitrb/split |
10071929 | <NME> user_spec.rb
<BEF> # frozen_string_literal: true
require "spec_helper"
require "split/experiment_catalog"
require "split/experiment"
require "split/user"
describe Split::User do
let(:user_keys) { { "link_color" => "blue" } }
let(:context) { double(session: { split: user_keys }) }
let(:experiment) { Split::Experiment.new("link_color") }
before(:each) do
@subject = described_class.new(context)
end
it "delegates methods correctly" do
expect(@subject["link_color"]).to eq(@subject.user["link_color"])
end
context "#cleanup_old_versions!" do
let(:experiment_version) { "#{experiment.name}:1" }
let(:second_experiment_version) { "#{experiment.name}_another:1" }
let(:third_experiment_version) { "variation_of_#{experiment.name}:1" }
let(:user_keys) do
{
experiment_version => "blue",
second_experiment_version => "red",
third_experiment_version => "yellow"
}
end
before(:each) { @subject.cleanup_old_versions!(experiment) }
it "removes key if old experiment is found" do
expect(@subject.keys).not_to include(experiment_version)
end
it "does not remove other keys" do
expect(@subject.keys).to include(second_experiment_version, third_experiment_version)
end
end
allow(experiment).to receive(:has_winner?).and_return(false)
@subject.cleanup_old_experiments!
expect(@subject.keys).to be_empty
end
end
end
context "with finished key" do
let(:user_keys) { { "link_color" => "blue", "link_color:finished" => true } }
it "does not remove finished key for experiment without a winner" do
allow(Split::ExperimentCatalog).to receive(:find).with("link_color").and_return(experiment)
allow(Split::ExperimentCatalog).to receive(:find).with("link_color:finished").and_return(nil)
allow(experiment).to receive(:start_time).and_return(Date.today)
allow(experiment).to receive(:has_winner?).and_return(false)
@subject.cleanup_old_experiments!
expect(@subject.keys).to include("link_color")
expect(@subject.keys).to include("link_color:finished")
end
end
context "when already cleaned up" do
before do
@subject.cleanup_old_experiments!
end
it "does not clean up again" do
expect(@subject).to_not receive(:keys_without_finished)
@subject.cleanup_old_experiments!
end
end
end
context "allows user to be loaded from adapter" do
it "loads user from adapter (RedisAdapter)" do
user = Split::Persistence::RedisAdapter.new(nil, 112233)
user["foo"] = "bar"
ab_user = Split::User.find(112233, :redis)
expect(ab_user["foo"]).to eql("bar")
end
it "returns nil if adapter does not implement a finder method" do
ab_user = Split::User.find(112233, :dual_adapter)
expect(ab_user).to be_nil
end
end
context "instantiated with custom adapter" do
let(:custom_adapter) { double(:persistence_adapter) }
before do
@subject = described_class.new(context, custom_adapter)
end
it "sets user to the custom adapter" do
expect(@subject.user).to eq(custom_adapter)
end
end
end
<MSG> FIX Negative numbers on non-finished
This fixes a major bug when negative non-finished numbers appear and simple random exception fired on dashboard.
The problem was with User#cleanup_old_experiments! method because it treats “experimen1:finished” key as a non-found experiment and just deletes it.
Related issues:
https://github.com/splitrb/split/issues/43
https://github.com/splitrb/split/issues/103
https://github.com/splitrb/split/issues/133
https://github.com/splitrb/split/issues/355
https://github.com/splitrb/split/issues/294
https://github.com/splitrb/split/issues/272
<DFF> @@ -44,6 +44,20 @@ describe Split::User do
allow(experiment).to receive(:has_winner?).and_return(false)
@subject.cleanup_old_experiments!
expect(@subject.keys).to be_empty
- end
+ end
+
+ context 'with finished key' do
+ let(:user_keys) { { 'link_color' => 'blue', 'link_color:finished' => true } }
+
+ it 'does not remove finished key for experiment without a winner' do
+ allow(Split::ExperimentCatalog).to receive(:find).with('link_color').and_return(experiment)
+ allow(Split::ExperimentCatalog).to receive(:find).with('link_color:finished').and_return(nil)
+ allow(experiment).to receive(:start_time).and_return(Date.today)
+ allow(experiment).to receive(:has_winner?).and_return(false)
+ @subject.cleanup_old_experiments!
+ expect(@subject.keys).to include("link_color")
+ expect(@subject.keys).to include("link_color:finished")
+ end
+ end
end
-end
\ No newline at end of file
+end
| 16 | FIX Negative numbers on non-finished | 2 | .rb | rb | mit | splitrb/split |
10071930 | <NME> settings.py
<BEF> # Django settings for djangopypi project.
import os
DEBUG=True
TEMPLATE_DEBUG=True
LOCAL_DEVELOPMENT=True
ADMINS = (
# ('Your Name', '[email protected]'),
)
if LOCAL_DEVELOPMENT:
import sys
sys.path.append(os.path.dirname(__file__))
ADMINS = (
('chishop', '[email protected]'),
MANAGERS = ADMINS
DATABASE_ENGINE = 'sqlite3'
DATABASE_NAME = 'devdatabase.db'
DATABASE_USER = ''
DATABASE_PASSWORD = ''
DATABASE_HOST = ''
DATABASE_HOST = ''
DATABASE_PORT = ''
<MSG> Moved development settings into development.py instead of settings.py. Buildout.cfg uses development.py by default
<DFF> @@ -1,10 +1,6 @@
# Django settings for djangopypi project.
import os
-DEBUG=True
-TEMPLATE_DEBUG=True
-LOCAL_DEVELOPMENT=True
-
ADMINS = (
# ('Your Name', '[email protected]'),
)
@@ -18,8 +14,8 @@ DJANGOPYPI_ALLOW_VERSION_OVERWRITE = False
MANAGERS = ADMINS
-DATABASE_ENGINE = 'sqlite3'
-DATABASE_NAME = 'devdatabase.db'
+DATABASE_ENGINE = ''
+DATABASE_NAME = ''
DATABASE_USER = ''
DATABASE_PASSWORD = ''
DATABASE_HOST = ''
| 2 | Moved development settings into development.py instead of settings.py. Buildout.cfg uses development.py by default | 6 | .py | py | bsd-3-clause | ask/chishop |
10071931 | <NME> urls.py
<BEF> # -*- coding: utf-8 -*-
from django.conf.urls.defaults import patterns, url, include
urlpatterns = patterns("djangopypi.views",
# Simple PyPI
url(r'^$', "simple",
name="djangopypi-simple"),
url(r'^(?P<dist_name>[\w\d_\.\-]+)/(?P<version>[\w\.\d\-_]+)/$',
"show_version",
name="djangopypi-show_version"),
url(r'^(?P<dist_name>[\w\d_\.\-]+)/$', "show_links",
name="djangopypi-show_links"),
)
)
<MSG> added simple pretty interface using the admin css.
<DFF> @@ -3,14 +3,21 @@ from django.conf.urls.defaults import patterns, url, include
urlpatterns = patterns("djangopypi.views",
# Simple PyPI
- url(r'^$', "simple",
+ url(r'^simple/$', "simple",
name="djangopypi-simple"),
- url(r'^(?P<dist_name>[\w\d_\.\-]+)/(?P<version>[\w\.\d\-_]+)/$',
+ url(r'^simple/(?P<dist_name>[\w\d_\.\-]+)/(?P<version>[\w\.\d\-_]+)/$',
"show_version",
name="djangopypi-show_version"),
- url(r'^(?P<dist_name>[\w\d_\.\-]+)/$', "show_links",
+ url(r'^simple/(?P<dist_name>[\w\d_\.\-]+)/$', "show_links",
name="djangopypi-show_links"),
+
+ url(r'^$', "simple", {'template_name': 'djangopypi/pypi.html'},
+ name="djangopypi-pypi"),
+
+ url(r'^(?P<dist_name>[\w\d_\.\-]+)/$', "show_links",
+ {'template_name': 'djangopypi/pypi_show_links.html'},
+ name="djangopypi-pypi_show_links"),
)
| 10 | added simple pretty interface using the admin css. | 3 | .py | py | bsd-3-clause | ask/chishop |
10071932 | <NME> matchers.js
<BEF> ADDFILE
<MSG> chore(jasmine): Added custom matcher
<DFF> @@ -0,0 +1,24 @@
+beforeEach(function() {
+'use strict';
+
+ jasmine.addMatchers({
+
+ toHaveClass: function() {
+ return {
+ compare: function(actual, expected) {
+ var result = {};
+
+ result.pass = actual.hasClass(expected);
+
+ if (result.pass) {
+ result.message = "Expected '" + angular.mock.dump(actual) + "' to have class '" + expected + "'.";
+ } else {
+ result.message = "Expected element to have class '" + expected + "' but got '" + angular.mock.dump(actual) + "'.";
+ }
+ return result;
+ }
+ }
+ }
+
+ });
+});
| 24 | chore(jasmine): Added custom matcher | 0 | .js | js | mit | Semantic-Org/Semantic-UI-Angular |
10071933 | <NME> matchers.js
<BEF> ADDFILE
<MSG> chore(jasmine): Added custom matcher
<DFF> @@ -0,0 +1,24 @@
+beforeEach(function() {
+'use strict';
+
+ jasmine.addMatchers({
+
+ toHaveClass: function() {
+ return {
+ compare: function(actual, expected) {
+ var result = {};
+
+ result.pass = actual.hasClass(expected);
+
+ if (result.pass) {
+ result.message = "Expected '" + angular.mock.dump(actual) + "' to have class '" + expected + "'.";
+ } else {
+ result.message = "Expected element to have class '" + expected + "' but got '" + angular.mock.dump(actual) + "'.";
+ }
+ return result;
+ }
+ }
+ }
+
+ });
+});
| 24 | chore(jasmine): Added custom matcher | 0 | .js | js | mit | Semantic-Org/Semantic-UI-Angular |
10071934 | <NME> matchers.js
<BEF> ADDFILE
<MSG> chore(jasmine): Added custom matcher
<DFF> @@ -0,0 +1,24 @@
+beforeEach(function() {
+'use strict';
+
+ jasmine.addMatchers({
+
+ toHaveClass: function() {
+ return {
+ compare: function(actual, expected) {
+ var result = {};
+
+ result.pass = actual.hasClass(expected);
+
+ if (result.pass) {
+ result.message = "Expected '" + angular.mock.dump(actual) + "' to have class '" + expected + "'.";
+ } else {
+ result.message = "Expected element to have class '" + expected + "' but got '" + angular.mock.dump(actual) + "'.";
+ }
+ return result;
+ }
+ }
+ }
+
+ });
+});
| 24 | chore(jasmine): Added custom matcher | 0 | .js | js | mit | Semantic-Org/Semantic-UI-Angular |
10071935 | <NME> user_spec.rb
<BEF> # frozen_string_literal: true
require "spec_helper"
require "split/experiment_catalog"
require "split/experiment"
require "split/user"
describe Split::User do
let(:user_keys) { { "link_color" => "blue" } }
let(:context) { double(session: { split: user_keys }) }
let(:experiment) { Split::Experiment.new("link_color") }
before(:each) do
@subject = described_class.new(context)
end
it "delegates methods correctly" do
expect(@subject["link_color"]).to eq(@subject.user["link_color"])
end
context "#cleanup_old_versions!" do
let(:experiment_version) { "#{experiment.name}:1" }
let(:second_experiment_version) { "#{experiment.name}_another:1" }
let(:third_experiment_version) { "variation_of_#{experiment.name}:1" }
let(:user_keys) do
{
experiment_version => "blue",
second_experiment_version => "red",
third_experiment_version => "yellow"
}
end
before(:each) { @subject.cleanup_old_versions!(experiment) }
it "removes key if old experiment is found" do
expect(@subject.keys).not_to include(experiment_version)
end
it "does not remove other keys" do
expect(@subject.keys).to include(second_experiment_version, third_experiment_version)
end
end
context "#cleanup_old_experiments!" do
it "removes key if experiment is not found" do
@subject.cleanup_old_experiments!
expect(@subject.keys).to be_empty
end
it "removes key if experiment has a winner" do
allow(Split::ExperimentCatalog).to receive(:find).with("link_color").and_return(experiment)
allow(experiment).to receive(:start_time).and_return(Date.today)
allow(experiment).to receive(:has_winner?).and_return(true)
@subject.cleanup_old_experiments!
expect(@subject.keys).to be_empty
end
it "removes key if experiment has not started yet" do
expect(@subject.keys).to include("link_color:finished")
end
end
end
context "instantiated with custom adapter" do
end
end
context "when already cleaned up" do
before do
@subject.cleanup_old_experiments!
end
it "does not clean up again" do
expect(@subject).to_not receive(:keys_without_finished)
@subject.cleanup_old_experiments!
end
end
end
context "allows user to be loaded from adapter" do
it "loads user from adapter (RedisAdapter)" do
user = Split::Persistence::RedisAdapter.new(nil, 112233)
user["foo"] = "bar"
ab_user = Split::User.find(112233, :redis)
expect(ab_user["foo"]).to eql("bar")
end
it "returns nil if adapter does not implement a finder method" do
ab_user = Split::User.find(112233, :dual_adapter)
expect(ab_user).to be_nil
end
end
context "instantiated with custom adapter" do
let(:custom_adapter) { double(:persistence_adapter) }
before do
@subject = described_class.new(context, custom_adapter)
end
it "sets user to the custom adapter" do
expect(@subject.user).to eq(custom_adapter)
end
end
end
<MSG> Merge pull request #575 from gnanou/combined_experiment_performance
Combined experiment performance improvements
<DFF> @@ -59,6 +59,17 @@ describe Split::User do
expect(@subject.keys).to include("link_color:finished")
end
end
+
+ context 'when already cleaned up' do
+ before do
+ @subject.cleanup_old_experiments!
+ end
+
+ it 'does not clean up again' do
+ expect(@subject).to_not receive(:keys_without_finished)
+ @subject.cleanup_old_experiments!
+ end
+ end
end
context "instantiated with custom adapter" do
| 11 | Merge pull request #575 from gnanou/combined_experiment_performance | 0 | .rb | rb | mit | splitrb/split |
10071936 | <NME> user_spec.rb
<BEF> # frozen_string_literal: true
require "spec_helper"
require "split/experiment_catalog"
require "split/experiment"
require "split/user"
describe Split::User do
let(:user_keys) { { "link_color" => "blue" } }
let(:context) { double(session: { split: user_keys }) }
let(:experiment) { Split::Experiment.new("link_color") }
before(:each) do
@subject = described_class.new(context)
end
it "delegates methods correctly" do
expect(@subject["link_color"]).to eq(@subject.user["link_color"])
end
context "#cleanup_old_versions!" do
let(:experiment_version) { "#{experiment.name}:1" }
let(:second_experiment_version) { "#{experiment.name}_another:1" }
let(:third_experiment_version) { "variation_of_#{experiment.name}:1" }
let(:user_keys) do
{
experiment_version => "blue",
second_experiment_version => "red",
third_experiment_version => "yellow"
}
end
before(:each) { @subject.cleanup_old_versions!(experiment) }
it "removes key if old experiment is found" do
expect(@subject.keys).not_to include(experiment_version)
end
it "does not remove other keys" do
expect(@subject.keys).to include(second_experiment_version, third_experiment_version)
end
end
context "#cleanup_old_experiments!" do
it "removes key if experiment is not found" do
@subject.cleanup_old_experiments!
expect(@subject.keys).to be_empty
end
it "removes key if experiment has a winner" do
allow(Split::ExperimentCatalog).to receive(:find).with("link_color").and_return(experiment)
allow(experiment).to receive(:start_time).and_return(Date.today)
allow(experiment).to receive(:has_winner?).and_return(true)
@subject.cleanup_old_experiments!
expect(@subject.keys).to be_empty
end
it "removes key if experiment has not started yet" do
expect(@subject.keys).to include("link_color:finished")
end
end
end
context "instantiated with custom adapter" do
end
end
context "when already cleaned up" do
before do
@subject.cleanup_old_experiments!
end
it "does not clean up again" do
expect(@subject).to_not receive(:keys_without_finished)
@subject.cleanup_old_experiments!
end
end
end
context "allows user to be loaded from adapter" do
it "loads user from adapter (RedisAdapter)" do
user = Split::Persistence::RedisAdapter.new(nil, 112233)
user["foo"] = "bar"
ab_user = Split::User.find(112233, :redis)
expect(ab_user["foo"]).to eql("bar")
end
it "returns nil if adapter does not implement a finder method" do
ab_user = Split::User.find(112233, :dual_adapter)
expect(ab_user).to be_nil
end
end
context "instantiated with custom adapter" do
let(:custom_adapter) { double(:persistence_adapter) }
before do
@subject = described_class.new(context, custom_adapter)
end
it "sets user to the custom adapter" do
expect(@subject.user).to eq(custom_adapter)
end
end
end
<MSG> Merge pull request #575 from gnanou/combined_experiment_performance
Combined experiment performance improvements
<DFF> @@ -59,6 +59,17 @@ describe Split::User do
expect(@subject.keys).to include("link_color:finished")
end
end
+
+ context 'when already cleaned up' do
+ before do
+ @subject.cleanup_old_experiments!
+ end
+
+ it 'does not clean up again' do
+ expect(@subject).to_not receive(:keys_without_finished)
+ @subject.cleanup_old_experiments!
+ end
+ end
end
context "instantiated with custom adapter" do
| 11 | Merge pull request #575 from gnanou/combined_experiment_performance | 0 | .rb | rb | mit | splitrb/split |
10071937 | <NME> user_spec.rb
<BEF> # frozen_string_literal: true
require "spec_helper"
require "split/experiment_catalog"
require "split/experiment"
require "split/user"
describe Split::User do
let(:user_keys) { { "link_color" => "blue" } }
let(:context) { double(session: { split: user_keys }) }
let(:experiment) { Split::Experiment.new("link_color") }
before(:each) do
@subject = described_class.new(context)
end
it "delegates methods correctly" do
expect(@subject["link_color"]).to eq(@subject.user["link_color"])
end
context "#cleanup_old_versions!" do
let(:experiment_version) { "#{experiment.name}:1" }
let(:second_experiment_version) { "#{experiment.name}_another:1" }
let(:third_experiment_version) { "variation_of_#{experiment.name}:1" }
let(:user_keys) do
{
experiment_version => "blue",
second_experiment_version => "red",
third_experiment_version => "yellow"
}
end
before(:each) { @subject.cleanup_old_versions!(experiment) }
it "removes key if old experiment is found" do
expect(@subject.keys).not_to include(experiment_version)
end
it "does not remove other keys" do
expect(@subject.keys).to include(second_experiment_version, third_experiment_version)
end
end
context "#cleanup_old_experiments!" do
it "removes key if experiment is not found" do
@subject.cleanup_old_experiments!
expect(@subject.keys).to be_empty
end
it "removes key if experiment has a winner" do
allow(Split::ExperimentCatalog).to receive(:find).with("link_color").and_return(experiment)
allow(experiment).to receive(:start_time).and_return(Date.today)
allow(experiment).to receive(:has_winner?).and_return(true)
@subject.cleanup_old_experiments!
expect(@subject.keys).to be_empty
end
it "removes key if experiment has not started yet" do
expect(@subject.keys).to include("link_color:finished")
end
end
end
context "instantiated with custom adapter" do
end
end
context "when already cleaned up" do
before do
@subject.cleanup_old_experiments!
end
it "does not clean up again" do
expect(@subject).to_not receive(:keys_without_finished)
@subject.cleanup_old_experiments!
end
end
end
context "allows user to be loaded from adapter" do
it "loads user from adapter (RedisAdapter)" do
user = Split::Persistence::RedisAdapter.new(nil, 112233)
user["foo"] = "bar"
ab_user = Split::User.find(112233, :redis)
expect(ab_user["foo"]).to eql("bar")
end
it "returns nil if adapter does not implement a finder method" do
ab_user = Split::User.find(112233, :dual_adapter)
expect(ab_user).to be_nil
end
end
context "instantiated with custom adapter" do
let(:custom_adapter) { double(:persistence_adapter) }
before do
@subject = described_class.new(context, custom_adapter)
end
it "sets user to the custom adapter" do
expect(@subject.user).to eq(custom_adapter)
end
end
end
<MSG> Merge pull request #575 from gnanou/combined_experiment_performance
Combined experiment performance improvements
<DFF> @@ -59,6 +59,17 @@ describe Split::User do
expect(@subject.keys).to include("link_color:finished")
end
end
+
+ context 'when already cleaned up' do
+ before do
+ @subject.cleanup_old_experiments!
+ end
+
+ it 'does not clean up again' do
+ expect(@subject).to_not receive(:keys_without_finished)
+ @subject.cleanup_old_experiments!
+ end
+ end
end
context "instantiated with custom adapter" do
| 11 | Merge pull request #575 from gnanou/combined_experiment_performance | 0 | .rb | rb | mit | splitrb/split |
10071938 | <NME> settings.py
<BEF> # Django settings for djangopypi project.
import os
DEBUG=True
TEMPLATE_DEBUG=True
LOCAL_DEVELOPMENT=True
ADMINS = (
# ('Your Name', '[email protected]'),
)
if LOCAL_DEVELOPMENT:
import sys
sys.path.append(os.path.dirname(__file__))
ADMINS = (
('chishop', '[email protected]'),
MANAGERS = ADMINS
DATABASE_ENGINE = 'sqlite3'
DATABASE_NAME = 'devdatabase.db'
DATABASE_USER = ''
DATABASE_PASSWORD = ''
DATABASE_HOST = ''
DATABASE_HOST = ''
DATABASE_PORT = ''
<MSG> Merge branch 'runeh/master'
<DFF> @@ -1,10 +1,6 @@
# Django settings for djangopypi project.
import os
-DEBUG=True
-TEMPLATE_DEBUG=True
-LOCAL_DEVELOPMENT=True
-
ADMINS = (
# ('Your Name', '[email protected]'),
)
@@ -18,8 +14,8 @@ DJANGOPYPI_ALLOW_VERSION_OVERWRITE = False
MANAGERS = ADMINS
-DATABASE_ENGINE = 'sqlite3'
-DATABASE_NAME = 'devdatabase.db'
+DATABASE_ENGINE = ''
+DATABASE_NAME = ''
DATABASE_USER = ''
DATABASE_PASSWORD = ''
DATABASE_HOST = ''
| 2 | Merge branch 'runeh/master' | 6 | .py | py | bsd-3-clause | ask/chishop |
10071939 | <NME> expand.ts
<BEF> import { strictEqual as equal } from 'assert';
import expand, { resolveConfig } from '../src';
describe('Expand Abbreviation', () => {
describe('Markup', () => {
it('basic', () => {
equal(expand('input[value="text$"]*2'), '<input type="text" value="text1"><input type="text" value="text2">');
equal(expand('ul>.item$*2'), '<ul>\n\t<li class="item1"></li>\n\t<li class="item2"></li>\n</ul>');
// insert text into abbreviation
equal(expand('ul>.item$*', { text: ['foo', 'bar'] }), '<ul>\n\t<li class="item1">foo</li>\n\t<li class="item2">bar</li>\n</ul>');
// insert TextMate-style fields/tabstops in output
equal(expand('ul>.item$*2', {
options: {
'output.field': (index, placeholder) => `\${${index}${placeholder ? ':' + placeholder : ''}}`
}
}), '<ul>\n\t<li class="item1">${1}</li>\n\t<li class="item2">${2}</li>\n</ul>');
});
it('attributes', () => {
const snippets = {
test: 'test[!foo bar. baz={}]'
};
const opt = { snippets };
const reverse = {
options: { 'output.reverseAttributes': true },
snippets
};
equal(expand('a.test'), '<a href="" class="test"></a>');
equal(expand('a.test', reverse), '<a class="test" href=""></a>');
equal(expand('test', opt), '<test bar="bar" baz={}></test>');
equal(expand('test[foo]', opt), '<test bar="bar" baz={}></test>');
equal(expand('test[baz=a foo=1]', opt), '<test foo="1" bar="bar" baz={a}></test>');
equal(expand('map'), '<map name=""></map>');
equal(expand('map[]'), '<map name=""></map>');
equal(expand('map[name="valid"]'), '<map name="valid"></map>');
equal(expand('map[href="invalid"]'), '<map name="" href="invalid"></map>');
// Apply attributes in reverse order
equal(expand('test', reverse), '<test bar="bar" baz={}></test>');
equal(expand('test[foo]', reverse), '<test bar="bar" baz={}></test>');
equal(expand('test[baz=a foo=1]', reverse), '<test baz={a} foo="1" bar="bar"></test>');
});
it('numbering', () => {
equal(expand('ul>li.item$@-*5'), '<ul>\n\t<li class="item5"></li>\n\t<li class="item4"></li>\n\t<li class="item3"></li>\n\t<li class="item2"></li>\n\t<li class="item1"></li>\n</ul>');
});
it('syntax', () => {
equal(expand('ul>.item$*2', { syntax: 'html' }), '<ul>\n\t<li class="item1"></li>\n\t<li class="item2"></li>\n</ul>');
equal(expand('ul>.item$*2', { syntax: 'slim' }), 'ul\n\tli.item1 \n\tli.item2 ');
equal(expand('xsl:variable[name=a select=b]>div', { syntax: 'xsl' }), '<xsl:variable name="a">\n\t<div></div>\n</xsl:variable>');
});
it('custom profile', () => {
equal(expand('img'), '<img src="" alt="">');
equal(expand('img', { options: { 'output.selfClosingStyle': 'xhtml' } }), '<img src="" alt="" />');
});
it('custom variables', () => {
const variables = { charset: 'ru-RU' };
equal(expand('[charset=${charset}]{${charset}}'), '<div charset="UTF-8">UTF-8</div>');
equal(expand('[charset=${charset}]{${charset}}', { variables }), '<div charset="ru-RU">ru-RU</div>');
});
it('custom snippets', () => {
const snippets = {
link: 'link[foo=bar href]/',
foo: '.foo[bar=baz]',
repeat: 'div>ul>li{Hello World}*3'
};
equal(expand('foo', { snippets }), '<div class="foo" bar="baz"></div>');
// `link:css` depends on `link` snippet so changing it will result in
// altered `link:css` result
equal(expand('link:css'), '<link rel="stylesheet" href="style.css">');
equal(expand('link:css', { snippets }), '<link foo="bar" href="style.css">');
// https://github.com/emmetio/emmet/issues/468
equal(expand('repeat', { snippets }), '<div>\n\t<ul>\n\t\t<li>Hello World</li>\n\t\t<li>Hello World</li>\n\t\t<li>Hello World</li>\n\t</ul>\n</div>');
});
it('formatter options', () => {
equal(expand('ul>.item$*2'), '<ul>\n\t<li class="item1"></li>\n\t<li class="item2"></li>\n</ul>');
equal(expand('ul>.item$*2', { options: { 'comment.enabled': true } }),
'<ul>\n\t<li class="item1"></li>\n\t<!-- /.item1 -->\n\t<li class="item2"></li>\n\t<!-- /.item2 -->\n</ul>');
equal(expand('div>p'), '<div>\n\t<p></p>\n</div>');
equal(expand('div>p', { options: { 'output.formatLeafNode': true } }), '<div>\n\t<p>\n\t\t\n\t</p>\n</div>');
});
it('JSX', () => {
const config = { syntax: 'jsx' };
equal(expand('div#foo.bar', config), '<div id="foo" className="bar"></div>');
it('wrap with abbreviation', () => {
equal(expand('div>ul', { text: ['<div>line1</div>\n<div>line2</div>'] }),
'<div>\n\t<ul>\n\t\t<div>line1</div>\n\t\t<div>line2</div>\n\t</ul>\n</div>');
});
// it.only('debug', () => {
equal(expand('..bar', config), '<div styleName={styles.bar}></div>');
equal(expand('..foo-bar', config), '<div styleName={styles[\'foo-bar\']}></div>');
equal(expand('.foo', { syntax: 'vue' }), '<div class="foo"></div>');
equal(expand('..foo', { syntax: 'vue' }), '<div :class="foo"></div>');
});
it('wrap with abbreviation', () => {
equal(expand('div>ul', { text: ['<div>line1</div>\n<div>line2</div>'] }),
'<div>\n\t<ul>\n\t\t<div>line1</div>\n\t\t<div>line2</div>\n\t</ul>\n</div>');
equal(expand('p', { text: 'foo\nbar' }), '<p>\n\tfoo\n\tbar\n</p>');
equal(expand('p', { text: '<div>foo</div>' }), '<p>\n\t<div>foo</div>\n</p>');
equal(expand('p', { text: '<span>foo</span>' }), '<p><span>foo</span></p>');
equal(expand('p', { text: 'foo<span>foo</span>' }), '<p>foo<span>foo</span></p>');
equal(expand('p', { text: 'foo<div>foo</div>' }), '<p>foo<div>foo</div></p>');
});
it('wrap with abbreviation href', () => {
equal(expand('a', { text: ['www.google.it'] }), '<a href="http://www.google.it">www.google.it</a>');
equal(expand('a', { text: ['then www.google.it'] }), '<a href="">then www.google.it</a>');
equal(expand('a', { text: ['www.google.it'], options: { 'markup.href': false } }), '<a href="">www.google.it</a>');
equal(expand('map[name="https://example.com"]', { text: ['some text'] }),
'<map name="https://example.com">some text</map>');
equal(expand('map[href="https://example.com"]', { text: ['some text'] }),
'<map name="" href="https://example.com">some text</map>');
equal(expand('map[name="https://example.com"]>b', { text: ['some text'] }),
'<map name="https://example.com"><b>some text</b></map>');
equal(expand('a[href="https://example.com"]>b', { text: ['<u>some text false</u>'], options: { 'markup.href': false } }),
'<a href="https://example.com"><b><u>some text false</u></b></a>');
equal(expand('a[href="https://example.com"]>b', { text: ['<u>some text true</u>'], options: { 'markup.href': true } }),
'<a href="https://example.com"><b><u>some text true</u></b></a>');
equal(expand('a[href="https://example.com"]>div', { text: ['<p>some text false</p>'], options: { 'markup.href': false } }),
'<a href="https://example.com">\n\t<div>\n\t\t<p>some text false</p>\n\t</div>\n</a>');
equal(expand('a[href="https://example.com"]>div', { text: ['<p>some text true</p>'], options: { 'markup.href': true } }),
'<a href="https://example.com">\n\t<div>\n\t\t<p>some text true</p>\n\t</div>\n</a>');
});
// it.only('debug', () => {
// equal(expand('link:css'), '<link rel="stylesheet" href="style.css">');
// });
});
describe('Pug templates', () => {
const config = resolveConfig({ syntax: 'pug' });
it('basic', () => {
equal(expand('!', config), 'doctype html\nhtml(lang="en")\n\thead\n\t\tmeta(charset="UTF-8")\n\t\tmeta(http-equiv="X-UA-Compatible", content="IE=edge")\n\t\tmeta(name="viewport", content="width=device-width, initial-scale=1.0")\n\t\ttitle Document\n\tbody ');
});
});
});
<MSG> Fix #611 (#612)
<DFF> @@ -101,6 +101,8 @@ describe('Expand Abbreviation', () => {
it('wrap with abbreviation', () => {
equal(expand('div>ul', { text: ['<div>line1</div>\n<div>line2</div>'] }),
'<div>\n\t<ul>\n\t\t<div>line1</div>\n\t\t<div>line2</div>\n\t</ul>\n</div>');
+ equal(expand('p', { text: 'foo\nbar'}), '<p>\n\tfoo\n\tbar\n</p>');
+ equal(expand('p', { text: '<div>foo</div>'}), '<p>\n\t<div>foo</div>\n</p>');
});
// it.only('debug', () => {
| 2 | Fix #611 (#612) | 0 | .ts | ts | mit | emmetio/emmet |
10071940 | <NME> expand.ts
<BEF> import { strictEqual as equal } from 'assert';
import expand, { resolveConfig } from '../src';
describe('Expand Abbreviation', () => {
describe('Markup', () => {
it('basic', () => {
equal(expand('input[value="text$"]*2'), '<input type="text" value="text1"><input type="text" value="text2">');
equal(expand('ul>.item$*2'), '<ul>\n\t<li class="item1"></li>\n\t<li class="item2"></li>\n</ul>');
// insert text into abbreviation
equal(expand('ul>.item$*', { text: ['foo', 'bar'] }), '<ul>\n\t<li class="item1">foo</li>\n\t<li class="item2">bar</li>\n</ul>');
// insert TextMate-style fields/tabstops in output
equal(expand('ul>.item$*2', {
options: {
'output.field': (index, placeholder) => `\${${index}${placeholder ? ':' + placeholder : ''}}`
}
}), '<ul>\n\t<li class="item1">${1}</li>\n\t<li class="item2">${2}</li>\n</ul>');
});
it('attributes', () => {
const snippets = {
test: 'test[!foo bar. baz={}]'
};
const opt = { snippets };
const reverse = {
options: { 'output.reverseAttributes': true },
snippets
};
equal(expand('a.test'), '<a href="" class="test"></a>');
equal(expand('a.test', reverse), '<a class="test" href=""></a>');
equal(expand('test', opt), '<test bar="bar" baz={}></test>');
equal(expand('test[foo]', opt), '<test bar="bar" baz={}></test>');
equal(expand('test[baz=a foo=1]', opt), '<test foo="1" bar="bar" baz={a}></test>');
equal(expand('map'), '<map name=""></map>');
equal(expand('map[]'), '<map name=""></map>');
equal(expand('map[name="valid"]'), '<map name="valid"></map>');
equal(expand('map[href="invalid"]'), '<map name="" href="invalid"></map>');
// Apply attributes in reverse order
equal(expand('test', reverse), '<test bar="bar" baz={}></test>');
equal(expand('test[foo]', reverse), '<test bar="bar" baz={}></test>');
equal(expand('test[baz=a foo=1]', reverse), '<test baz={a} foo="1" bar="bar"></test>');
});
it('numbering', () => {
equal(expand('ul>li.item$@-*5'), '<ul>\n\t<li class="item5"></li>\n\t<li class="item4"></li>\n\t<li class="item3"></li>\n\t<li class="item2"></li>\n\t<li class="item1"></li>\n</ul>');
});
it('syntax', () => {
equal(expand('ul>.item$*2', { syntax: 'html' }), '<ul>\n\t<li class="item1"></li>\n\t<li class="item2"></li>\n</ul>');
equal(expand('ul>.item$*2', { syntax: 'slim' }), 'ul\n\tli.item1 \n\tli.item2 ');
equal(expand('xsl:variable[name=a select=b]>div', { syntax: 'xsl' }), '<xsl:variable name="a">\n\t<div></div>\n</xsl:variable>');
});
it('custom profile', () => {
equal(expand('img'), '<img src="" alt="">');
equal(expand('img', { options: { 'output.selfClosingStyle': 'xhtml' } }), '<img src="" alt="" />');
});
it('custom variables', () => {
const variables = { charset: 'ru-RU' };
equal(expand('[charset=${charset}]{${charset}}'), '<div charset="UTF-8">UTF-8</div>');
equal(expand('[charset=${charset}]{${charset}}', { variables }), '<div charset="ru-RU">ru-RU</div>');
});
it('custom snippets', () => {
const snippets = {
link: 'link[foo=bar href]/',
foo: '.foo[bar=baz]',
repeat: 'div>ul>li{Hello World}*3'
};
equal(expand('foo', { snippets }), '<div class="foo" bar="baz"></div>');
// `link:css` depends on `link` snippet so changing it will result in
// altered `link:css` result
equal(expand('link:css'), '<link rel="stylesheet" href="style.css">');
equal(expand('link:css', { snippets }), '<link foo="bar" href="style.css">');
// https://github.com/emmetio/emmet/issues/468
equal(expand('repeat', { snippets }), '<div>\n\t<ul>\n\t\t<li>Hello World</li>\n\t\t<li>Hello World</li>\n\t\t<li>Hello World</li>\n\t</ul>\n</div>');
});
it('formatter options', () => {
equal(expand('ul>.item$*2'), '<ul>\n\t<li class="item1"></li>\n\t<li class="item2"></li>\n</ul>');
equal(expand('ul>.item$*2', { options: { 'comment.enabled': true } }),
'<ul>\n\t<li class="item1"></li>\n\t<!-- /.item1 -->\n\t<li class="item2"></li>\n\t<!-- /.item2 -->\n</ul>');
equal(expand('div>p'), '<div>\n\t<p></p>\n</div>');
equal(expand('div>p', { options: { 'output.formatLeafNode': true } }), '<div>\n\t<p>\n\t\t\n\t</p>\n</div>');
});
it('JSX', () => {
const config = { syntax: 'jsx' };
equal(expand('div#foo.bar', config), '<div id="foo" className="bar"></div>');
it('wrap with abbreviation', () => {
equal(expand('div>ul', { text: ['<div>line1</div>\n<div>line2</div>'] }),
'<div>\n\t<ul>\n\t\t<div>line1</div>\n\t\t<div>line2</div>\n\t</ul>\n</div>');
});
// it.only('debug', () => {
equal(expand('..bar', config), '<div styleName={styles.bar}></div>');
equal(expand('..foo-bar', config), '<div styleName={styles[\'foo-bar\']}></div>');
equal(expand('.foo', { syntax: 'vue' }), '<div class="foo"></div>');
equal(expand('..foo', { syntax: 'vue' }), '<div :class="foo"></div>');
});
it('wrap with abbreviation', () => {
equal(expand('div>ul', { text: ['<div>line1</div>\n<div>line2</div>'] }),
'<div>\n\t<ul>\n\t\t<div>line1</div>\n\t\t<div>line2</div>\n\t</ul>\n</div>');
equal(expand('p', { text: 'foo\nbar' }), '<p>\n\tfoo\n\tbar\n</p>');
equal(expand('p', { text: '<div>foo</div>' }), '<p>\n\t<div>foo</div>\n</p>');
equal(expand('p', { text: '<span>foo</span>' }), '<p><span>foo</span></p>');
equal(expand('p', { text: 'foo<span>foo</span>' }), '<p>foo<span>foo</span></p>');
equal(expand('p', { text: 'foo<div>foo</div>' }), '<p>foo<div>foo</div></p>');
});
it('wrap with abbreviation href', () => {
equal(expand('a', { text: ['www.google.it'] }), '<a href="http://www.google.it">www.google.it</a>');
equal(expand('a', { text: ['then www.google.it'] }), '<a href="">then www.google.it</a>');
equal(expand('a', { text: ['www.google.it'], options: { 'markup.href': false } }), '<a href="">www.google.it</a>');
equal(expand('map[name="https://example.com"]', { text: ['some text'] }),
'<map name="https://example.com">some text</map>');
equal(expand('map[href="https://example.com"]', { text: ['some text'] }),
'<map name="" href="https://example.com">some text</map>');
equal(expand('map[name="https://example.com"]>b', { text: ['some text'] }),
'<map name="https://example.com"><b>some text</b></map>');
equal(expand('a[href="https://example.com"]>b', { text: ['<u>some text false</u>'], options: { 'markup.href': false } }),
'<a href="https://example.com"><b><u>some text false</u></b></a>');
equal(expand('a[href="https://example.com"]>b', { text: ['<u>some text true</u>'], options: { 'markup.href': true } }),
'<a href="https://example.com"><b><u>some text true</u></b></a>');
equal(expand('a[href="https://example.com"]>div', { text: ['<p>some text false</p>'], options: { 'markup.href': false } }),
'<a href="https://example.com">\n\t<div>\n\t\t<p>some text false</p>\n\t</div>\n</a>');
equal(expand('a[href="https://example.com"]>div', { text: ['<p>some text true</p>'], options: { 'markup.href': true } }),
'<a href="https://example.com">\n\t<div>\n\t\t<p>some text true</p>\n\t</div>\n</a>');
});
// it.only('debug', () => {
// equal(expand('link:css'), '<link rel="stylesheet" href="style.css">');
// });
});
describe('Pug templates', () => {
const config = resolveConfig({ syntax: 'pug' });
it('basic', () => {
equal(expand('!', config), 'doctype html\nhtml(lang="en")\n\thead\n\t\tmeta(charset="UTF-8")\n\t\tmeta(http-equiv="X-UA-Compatible", content="IE=edge")\n\t\tmeta(name="viewport", content="width=device-width, initial-scale=1.0")\n\t\ttitle Document\n\tbody ');
});
});
});
<MSG> Fix #611 (#612)
<DFF> @@ -101,6 +101,8 @@ describe('Expand Abbreviation', () => {
it('wrap with abbreviation', () => {
equal(expand('div>ul', { text: ['<div>line1</div>\n<div>line2</div>'] }),
'<div>\n\t<ul>\n\t\t<div>line1</div>\n\t\t<div>line2</div>\n\t</ul>\n</div>');
+ equal(expand('p', { text: 'foo\nbar'}), '<p>\n\tfoo\n\tbar\n</p>');
+ equal(expand('p', { text: '<div>foo</div>'}), '<p>\n\t<div>foo</div>\n</p>');
});
// it.only('debug', () => {
| 2 | Fix #611 (#612) | 0 | .ts | ts | mit | emmetio/emmet |
10071941 | <NME> stylesheet.ts
<BEF> import { strictEqual as equal, ok } from 'assert';
import { stylesheet as expandAbbreviation, resolveConfig } from '../src';
import score from '../src/stylesheet/score';
const defaultConfig = resolveConfig({
type: 'stylesheet',
options: {
'output.field': (index, placeholder) => `\${${index}${placeholder ? ':' + placeholder : ''}}`
},
snippets: {
mten: 'margin: 10px;',
fsz: 'font-size'
},
cache: {}
});
function expand(abbr: string, config = defaultConfig) {
function expand(abbr: string, config = defaultConfig) {
return expandAbbreviation(abbr, config);
}
describe('Stylesheet abbreviations', () => {
describe('Scoring', () => {
const pick = (abbr: string, items: string[]) => items
.map(item => ({ item, score: score(abbr, item) }))
.filter(obj => obj.score)
.sort((a, b) => b.score - a.score)
.map(obj => obj.item)[0];
.map(obj => obj.item)[0];
it('compare scores', () => {
equal(score('aaa', 'aaa'), 1);
equal(score('baa', 'aaa'), 0);
ok(!score('b', 'aaa'));
ok(score('a', 'aaa'));
ok(score('a', 'abc'));
ok(score('ac', 'abc'));
ok(score('a', 'aaa') < score('aa', 'aaa'));
ok(score('ab', 'abc') > score('ab', 'acb'));
// acronym bonus
ok(score('ab', 'a-b') > score('ab', 'acb'));
});
it('pick padding or position', () => {
const items = ['p', 'pb', 'pl', 'pos', 'pa', 'oa', 'soa', 'pr', 'pt'];
equal(pick('p', items), 'p');
equal(pick('poa', items), 'pos');
});
});
it('keywords', () => {
equal(expand('bd1-s'), 'border: 1px solid;');
equal(expand('dib'), 'display: inline-block;');
equal(expand('bxsz'), 'box-sizing: ${1:border-box};');
equal(expand('bxz'), 'box-sizing: ${1:border-box};');
equal(expand('bxzc'), 'box-sizing: content-box;');
equal(expand('fl'), 'float: ${1:left};');
equal(expand('fll'), 'float: left;');
equal(expand('pos'), 'position: ${1:relative};');
equal(expand('poa'), 'position: absolute;');
equal(expand('por'), 'position: relative;');
equal(expand('pof'), 'position: fixed;');
equal(expand('pos-a'), 'position: absolute;');
equal(expand('m'), 'margin: ${0};');
equal(expand('m0'), 'margin: 0;');
// use `auto` as global keyword
equal(expand('m0-a'), 'margin: 0 auto;');
equal(expand('m-a'), 'margin: auto;');
equal(expand('bg'), 'background: ${1:#000};');
equal(expand('bd'), 'border: ${1:1px} ${2:solid} ${3:#000};');
equal(expand('bd0-s#fc0'), 'border: 0 solid #fc0;');
equal(expand('bd0-dd#fc0'), 'border: 0 dot-dash #fc0;');
equal(expand('bd0-h#fc0'), 'border: 0 hidden #fc0;');
equal(expand('trf-trs'), 'transform: translate(${1:x}, ${2:y});');
// https://github.com/emmetio/emmet/issues/610
equal(expand('c'), 'color: ${1:#000};');
equal(expand('cr'), 'color: rgb(${1:0}, ${2:0}, ${3:0});');
equal(expand('cra'), 'color: rgba(${1:0}, ${2:0}, ${3:0}, ${4:.5});');
// https://github.com/emmetio/emmet/issues/647
equal(expand('gtc'), 'grid-template-columns: repeat(${0});');
equal(expand('gtr'), 'grid-template-rows: repeat(${0});');
equal(expand('lis:n'), 'list-style: none;');
equal(expand('list:n'), 'list-style-type: none;');
equal(expand('bdt:n'), 'border-top: none;');
equal(expand('bgi:n'), 'background-image: none;');
equal(expand('q:n'), 'quotes: none;');
});
it('numeric', () => {
equal(expand('p0'), 'padding: 0;', 'No unit for 0');
equal(expand('p10'), 'padding: 10px;', '`px` unit for integers');
equal(expand('p.4'), 'padding: 0.4em;', '`em` for floats');
equal(expand('fz10'), 'font-size: 10px;', '`px` for integers');
equal(expand('fz1.'), 'font-size: 1em;', '`em` for explicit float');
equal(expand('p10p'), 'padding: 10%;', 'unit alias');
equal(expand('z10'), 'z-index: 10;', 'Unitless property');
equal(expand('p10r'), 'padding: 10rem;', 'unit alias');
equal(expand('mten'), 'margin: 10px;', 'Ignore terminating `;` in snippet');
// https://github.com/microsoft/vscode/issues/59951
equal(expand('fz'), 'font-size: ${0};');
equal(expand('fz12'), 'font-size: 12px;');
equal(expand('fsz'), 'font-size: ${0};');
equal(expand('fsz12'), 'font-size: 12px;');
equal(expand('fs'), 'font-style: ${1:italic};');
// https://github.com/emmetio/emmet/issues/558
equal(expand('us'), 'user-select: none;');
// https://github.com/microsoft/vscode/issues/105697
equal(expand('opa1'), 'opacity: 1;', 'Unitless property');
equal(expand('opa.1'), 'opacity: 0.1;', 'Unitless property');
equal(expand('opa.a'), 'opacity: .a;', 'Unitless property');
});
it('numeric with format options', () => {
const config = resolveConfig({
type: 'stylesheet',
options: {
'stylesheet.intUnit': 'pt',
});
it('snippets', () => {
equal(expand('@k'), '@keyframes ${1:identifier} {\n\t${2}\n}');
// Insert value into snippet fields
equal(expand('@k-name'), '@keyframes name {\n\t${2}\n}');
equal(expand('@k-name10'), '@keyframes name {\n\t10\n}');
});
equal(expand('p0', config), 'padding: 0;', 'No unit for 0');
equal(expand('p10', config), 'padding: 10pt;', '`pt` unit for integers');
equal(expand('p.4', config), 'padding: 0.4vh;', '`vh` for floats');
equal(expand('p10p', config), 'padding: 10%;', 'unit alias');
equal(expand('z10', config), 'z-index: 10;', 'Unitless property');
equal(expand('p10r', config), 'padding: 10 / @rem;', 'unit alias');
});
it('important', () => {
equal(expand('!'), '!important');
equal(expand('p!'), 'padding: ${0} !important;');
equal(expand('p0!'), 'padding: 0 !important;');
});
it('color', () => {
equal(expand('c'), 'color: ${1:#000};');
equal(expand('c#'), 'color: #000;');
equal(expand('lg(to right, #0, #f00.5)'), 'background-image: linear-gradient(to right, #000, rgba(255, 0, 0, 0.5));');
});
it('use min score when finding best match for snippets', () => {
equal(expand('auto', resolveConfig({
type: 'stylesheet',
options: { 'stylesheet.fuzzySearchMinScore': 0 }
})), 'align-self: unset;');
equal(expand('auto', resolveConfig({
type: 'stylesheet',
options: { 'stylesheet.fuzzySearchMinScore': 0.3 }
})), 'auto: ;');
});
it('CSS-in-JS', () => {
it('multiple properties', () => {
equal(expand('p10+m10-20'), 'padding: 10px;\nmargin: 10px 20px;');
equal(expand('p+bd'), 'padding: ${0};\nborder: ${1:1px} ${2:solid} ${3:#000};');
});
it('functions', () => {
equal(expand('trf-s(2)'), 'transform: scale(2, ${2:y});');
equal(expand('trf-s(2, 3)'), 'transform: scale(2, 3);');
});
it('case insensitive matches', () => {
equal(expand('trf:rx'), 'transform: rotateX(${1:angle});');
});
it('gradient resolver', () => {
equal(expand('lg'), 'background-image: linear-gradient(${0});');
equal(expand('lg(to right, #0, #f00.5)'), 'background-image: linear-gradient(to right, #000, rgba(255, 0, 0, 0.5));');
equal(expand('s', config), 'start');
equal(expand('a', config), 'auto');
});
});
context: { name: 'align-content' }
});
equal(expand('s', config), 'start');
equal(expand('a', config), 'auto');
});
it('limit snippets by scope', () => {
const sectionScope = resolveConfig({
type: 'stylesheet',
context: { name: CSSAbbreviationScope.Section },
snippets: {
mten: 'margin: 10px;',
fsz: 'font-size',
myCenterAwesome: 'body {\n\tdisplay: grid;\n}'
}
});
const propertyScope = resolveConfig({
type: 'stylesheet',
context: { name: CSSAbbreviationScope.Property },
snippets: {
mten: 'margin: 10px;',
fsz: 'font-size',
myCenterAwesome: 'body {\n\tdisplay: grid;\n}'
}
});
equal(expand('m', sectionScope), 'body {\n\tdisplay: grid;\n}');
equal(expand('b', sectionScope), '');
equal(expand('m', propertyScope), 'margin: ;');
});
});
<MSG> Updated CSS abbreviation scoring algorithm
Added scope for matching abbreviations
<DFF> @@ -1,17 +1,18 @@
import { strictEqual as equal, ok } from 'assert';
-import { stylesheet as expandAbbreviation, resolveConfig } from '../src';
+import { stylesheet as expandAbbreviation, resolveConfig, CSSAbbreviationScope } from '../src';
import score from '../src/stylesheet/score';
const defaultConfig = resolveConfig({
type: 'stylesheet',
options: {
- 'output.field': (index, placeholder) => `\${${index}${placeholder ? ':' + placeholder : ''}}`
+ 'output.field': (index, placeholder) => `\${${index}${placeholder ? ':' + placeholder : ''}}`,
+ 'stylesheet.fuzzySearchMinScore': 0
},
snippets: {
mten: 'margin: 10px;',
fsz: 'font-size'
},
- cache: {}
+ cache: {},
});
function expand(abbr: string, config = defaultConfig) {
@@ -21,7 +22,7 @@ function expand(abbr: string, config = defaultConfig) {
describe('Stylesheet abbreviations', () => {
describe('Scoring', () => {
const pick = (abbr: string, items: string[]) => items
- .map(item => ({ item, score: score(abbr, item) }))
+ .map(item => ({ item, score: score(abbr, item, true) }))
.filter(obj => obj.score)
.sort((a, b) => b.score - a.score)
.map(obj => obj.item)[0];
@@ -132,7 +133,8 @@ describe('Stylesheet abbreviations', () => {
});
it('snippets', () => {
- equal(expand('@k'), '@keyframes ${1:identifier} {\n\t${2}\n}');
+ equal(expand('@'), '@media ${1:screen} {\n\t${0}\n}');
+
// Insert value into snippet fields
equal(expand('@k-name'), '@keyframes name {\n\t${2}\n}');
equal(expand('@k-name10'), '@keyframes name {\n\t10\n}');
@@ -157,15 +159,14 @@ describe('Stylesheet abbreviations', () => {
equal(expand('lg(to right, #0, #f00.5)'), 'background-image: linear-gradient(to right, #000, rgba(255, 0, 0, 0.5));');
});
- it('use min score when finding best match for snippets', () => {
- equal(expand('auto', resolveConfig({
- type: 'stylesheet',
- options: { 'stylesheet.fuzzySearchMinScore': 0 }
- })), 'align-self: unset;');
- equal(expand('auto', resolveConfig({
- type: 'stylesheet',
- options: { 'stylesheet.fuzzySearchMinScore': 0.3 }
- })), 'auto: ;');
+ it('unmatched abbreviation', () => {
+ // This example is useless: it’s unexpected to receive `align-self: unset`
+ // for `auto` snippet
+ // equal(expand('auto', resolveConfig({
+ // type: 'stylesheet',
+ // options: { 'stylesheet.fuzzySearchMinScore': 0 }
+ // })), 'align-self: unset;');
+ equal(expand('auto'), 'auto: ${0};');
});
it('CSS-in-JS', () => {
@@ -189,4 +190,28 @@ describe('Stylesheet abbreviations', () => {
equal(expand('s', config), 'start');
equal(expand('a', config), 'auto');
});
+
+ it('limit snippets by scope', () => {
+ const sectionScope = resolveConfig({
+ type: 'stylesheet',
+ context: { name: CSSAbbreviationScope.Section },
+ snippets: {
+ mten: 'margin: 10px;',
+ fsz: 'font-size',
+ myCenterAwesome: 'body {\n\tdisplay: grid;\n}'
+ }
+ });
+ const propertyScope = resolveConfig({
+ type: 'stylesheet',
+ context: { name: CSSAbbreviationScope.Property },
+ snippets: {
+ mten: 'margin: 10px;',
+ fsz: 'font-size',
+ myCenterAwesome: 'body {\n\tdisplay: grid;\n}'
+ }
+ });
+
+ equal(expand('m', sectionScope), 'body {\n\tdisplay: grid;\n}');
+ equal(expand('m', propertyScope), 'margin: ;');
+ });
});
| 39 | Updated CSS abbreviation scoring algorithm | 14 | .ts | ts | mit | emmetio/emmet |
10071942 | <NME> stylesheet.ts
<BEF> import { strictEqual as equal, ok } from 'assert';
import { stylesheet as expandAbbreviation, resolveConfig } from '../src';
import score from '../src/stylesheet/score';
const defaultConfig = resolveConfig({
type: 'stylesheet',
options: {
'output.field': (index, placeholder) => `\${${index}${placeholder ? ':' + placeholder : ''}}`
},
snippets: {
mten: 'margin: 10px;',
fsz: 'font-size'
},
cache: {}
});
function expand(abbr: string, config = defaultConfig) {
function expand(abbr: string, config = defaultConfig) {
return expandAbbreviation(abbr, config);
}
describe('Stylesheet abbreviations', () => {
describe('Scoring', () => {
const pick = (abbr: string, items: string[]) => items
.map(item => ({ item, score: score(abbr, item) }))
.filter(obj => obj.score)
.sort((a, b) => b.score - a.score)
.map(obj => obj.item)[0];
.map(obj => obj.item)[0];
it('compare scores', () => {
equal(score('aaa', 'aaa'), 1);
equal(score('baa', 'aaa'), 0);
ok(!score('b', 'aaa'));
ok(score('a', 'aaa'));
ok(score('a', 'abc'));
ok(score('ac', 'abc'));
ok(score('a', 'aaa') < score('aa', 'aaa'));
ok(score('ab', 'abc') > score('ab', 'acb'));
// acronym bonus
ok(score('ab', 'a-b') > score('ab', 'acb'));
});
it('pick padding or position', () => {
const items = ['p', 'pb', 'pl', 'pos', 'pa', 'oa', 'soa', 'pr', 'pt'];
equal(pick('p', items), 'p');
equal(pick('poa', items), 'pos');
});
});
it('keywords', () => {
equal(expand('bd1-s'), 'border: 1px solid;');
equal(expand('dib'), 'display: inline-block;');
equal(expand('bxsz'), 'box-sizing: ${1:border-box};');
equal(expand('bxz'), 'box-sizing: ${1:border-box};');
equal(expand('bxzc'), 'box-sizing: content-box;');
equal(expand('fl'), 'float: ${1:left};');
equal(expand('fll'), 'float: left;');
equal(expand('pos'), 'position: ${1:relative};');
equal(expand('poa'), 'position: absolute;');
equal(expand('por'), 'position: relative;');
equal(expand('pof'), 'position: fixed;');
equal(expand('pos-a'), 'position: absolute;');
equal(expand('m'), 'margin: ${0};');
equal(expand('m0'), 'margin: 0;');
// use `auto` as global keyword
equal(expand('m0-a'), 'margin: 0 auto;');
equal(expand('m-a'), 'margin: auto;');
equal(expand('bg'), 'background: ${1:#000};');
equal(expand('bd'), 'border: ${1:1px} ${2:solid} ${3:#000};');
equal(expand('bd0-s#fc0'), 'border: 0 solid #fc0;');
equal(expand('bd0-dd#fc0'), 'border: 0 dot-dash #fc0;');
equal(expand('bd0-h#fc0'), 'border: 0 hidden #fc0;');
equal(expand('trf-trs'), 'transform: translate(${1:x}, ${2:y});');
// https://github.com/emmetio/emmet/issues/610
equal(expand('c'), 'color: ${1:#000};');
equal(expand('cr'), 'color: rgb(${1:0}, ${2:0}, ${3:0});');
equal(expand('cra'), 'color: rgba(${1:0}, ${2:0}, ${3:0}, ${4:.5});');
// https://github.com/emmetio/emmet/issues/647
equal(expand('gtc'), 'grid-template-columns: repeat(${0});');
equal(expand('gtr'), 'grid-template-rows: repeat(${0});');
equal(expand('lis:n'), 'list-style: none;');
equal(expand('list:n'), 'list-style-type: none;');
equal(expand('bdt:n'), 'border-top: none;');
equal(expand('bgi:n'), 'background-image: none;');
equal(expand('q:n'), 'quotes: none;');
});
it('numeric', () => {
equal(expand('p0'), 'padding: 0;', 'No unit for 0');
equal(expand('p10'), 'padding: 10px;', '`px` unit for integers');
equal(expand('p.4'), 'padding: 0.4em;', '`em` for floats');
equal(expand('fz10'), 'font-size: 10px;', '`px` for integers');
equal(expand('fz1.'), 'font-size: 1em;', '`em` for explicit float');
equal(expand('p10p'), 'padding: 10%;', 'unit alias');
equal(expand('z10'), 'z-index: 10;', 'Unitless property');
equal(expand('p10r'), 'padding: 10rem;', 'unit alias');
equal(expand('mten'), 'margin: 10px;', 'Ignore terminating `;` in snippet');
// https://github.com/microsoft/vscode/issues/59951
equal(expand('fz'), 'font-size: ${0};');
equal(expand('fz12'), 'font-size: 12px;');
equal(expand('fsz'), 'font-size: ${0};');
equal(expand('fsz12'), 'font-size: 12px;');
equal(expand('fs'), 'font-style: ${1:italic};');
// https://github.com/emmetio/emmet/issues/558
equal(expand('us'), 'user-select: none;');
// https://github.com/microsoft/vscode/issues/105697
equal(expand('opa1'), 'opacity: 1;', 'Unitless property');
equal(expand('opa.1'), 'opacity: 0.1;', 'Unitless property');
equal(expand('opa.a'), 'opacity: .a;', 'Unitless property');
});
it('numeric with format options', () => {
const config = resolveConfig({
type: 'stylesheet',
options: {
'stylesheet.intUnit': 'pt',
});
it('snippets', () => {
equal(expand('@k'), '@keyframes ${1:identifier} {\n\t${2}\n}');
// Insert value into snippet fields
equal(expand('@k-name'), '@keyframes name {\n\t${2}\n}');
equal(expand('@k-name10'), '@keyframes name {\n\t10\n}');
});
equal(expand('p0', config), 'padding: 0;', 'No unit for 0');
equal(expand('p10', config), 'padding: 10pt;', '`pt` unit for integers');
equal(expand('p.4', config), 'padding: 0.4vh;', '`vh` for floats');
equal(expand('p10p', config), 'padding: 10%;', 'unit alias');
equal(expand('z10', config), 'z-index: 10;', 'Unitless property');
equal(expand('p10r', config), 'padding: 10 / @rem;', 'unit alias');
});
it('important', () => {
equal(expand('!'), '!important');
equal(expand('p!'), 'padding: ${0} !important;');
equal(expand('p0!'), 'padding: 0 !important;');
});
it('color', () => {
equal(expand('c'), 'color: ${1:#000};');
equal(expand('c#'), 'color: #000;');
equal(expand('lg(to right, #0, #f00.5)'), 'background-image: linear-gradient(to right, #000, rgba(255, 0, 0, 0.5));');
});
it('use min score when finding best match for snippets', () => {
equal(expand('auto', resolveConfig({
type: 'stylesheet',
options: { 'stylesheet.fuzzySearchMinScore': 0 }
})), 'align-self: unset;');
equal(expand('auto', resolveConfig({
type: 'stylesheet',
options: { 'stylesheet.fuzzySearchMinScore': 0.3 }
})), 'auto: ;');
});
it('CSS-in-JS', () => {
it('multiple properties', () => {
equal(expand('p10+m10-20'), 'padding: 10px;\nmargin: 10px 20px;');
equal(expand('p+bd'), 'padding: ${0};\nborder: ${1:1px} ${2:solid} ${3:#000};');
});
it('functions', () => {
equal(expand('trf-s(2)'), 'transform: scale(2, ${2:y});');
equal(expand('trf-s(2, 3)'), 'transform: scale(2, 3);');
});
it('case insensitive matches', () => {
equal(expand('trf:rx'), 'transform: rotateX(${1:angle});');
});
it('gradient resolver', () => {
equal(expand('lg'), 'background-image: linear-gradient(${0});');
equal(expand('lg(to right, #0, #f00.5)'), 'background-image: linear-gradient(to right, #000, rgba(255, 0, 0, 0.5));');
equal(expand('s', config), 'start');
equal(expand('a', config), 'auto');
});
});
context: { name: 'align-content' }
});
equal(expand('s', config), 'start');
equal(expand('a', config), 'auto');
});
it('limit snippets by scope', () => {
const sectionScope = resolveConfig({
type: 'stylesheet',
context: { name: CSSAbbreviationScope.Section },
snippets: {
mten: 'margin: 10px;',
fsz: 'font-size',
myCenterAwesome: 'body {\n\tdisplay: grid;\n}'
}
});
const propertyScope = resolveConfig({
type: 'stylesheet',
context: { name: CSSAbbreviationScope.Property },
snippets: {
mten: 'margin: 10px;',
fsz: 'font-size',
myCenterAwesome: 'body {\n\tdisplay: grid;\n}'
}
});
equal(expand('m', sectionScope), 'body {\n\tdisplay: grid;\n}');
equal(expand('b', sectionScope), '');
equal(expand('m', propertyScope), 'margin: ;');
});
});
<MSG> Updated CSS abbreviation scoring algorithm
Added scope for matching abbreviations
<DFF> @@ -1,17 +1,18 @@
import { strictEqual as equal, ok } from 'assert';
-import { stylesheet as expandAbbreviation, resolveConfig } from '../src';
+import { stylesheet as expandAbbreviation, resolveConfig, CSSAbbreviationScope } from '../src';
import score from '../src/stylesheet/score';
const defaultConfig = resolveConfig({
type: 'stylesheet',
options: {
- 'output.field': (index, placeholder) => `\${${index}${placeholder ? ':' + placeholder : ''}}`
+ 'output.field': (index, placeholder) => `\${${index}${placeholder ? ':' + placeholder : ''}}`,
+ 'stylesheet.fuzzySearchMinScore': 0
},
snippets: {
mten: 'margin: 10px;',
fsz: 'font-size'
},
- cache: {}
+ cache: {},
});
function expand(abbr: string, config = defaultConfig) {
@@ -21,7 +22,7 @@ function expand(abbr: string, config = defaultConfig) {
describe('Stylesheet abbreviations', () => {
describe('Scoring', () => {
const pick = (abbr: string, items: string[]) => items
- .map(item => ({ item, score: score(abbr, item) }))
+ .map(item => ({ item, score: score(abbr, item, true) }))
.filter(obj => obj.score)
.sort((a, b) => b.score - a.score)
.map(obj => obj.item)[0];
@@ -132,7 +133,8 @@ describe('Stylesheet abbreviations', () => {
});
it('snippets', () => {
- equal(expand('@k'), '@keyframes ${1:identifier} {\n\t${2}\n}');
+ equal(expand('@'), '@media ${1:screen} {\n\t${0}\n}');
+
// Insert value into snippet fields
equal(expand('@k-name'), '@keyframes name {\n\t${2}\n}');
equal(expand('@k-name10'), '@keyframes name {\n\t10\n}');
@@ -157,15 +159,14 @@ describe('Stylesheet abbreviations', () => {
equal(expand('lg(to right, #0, #f00.5)'), 'background-image: linear-gradient(to right, #000, rgba(255, 0, 0, 0.5));');
});
- it('use min score when finding best match for snippets', () => {
- equal(expand('auto', resolveConfig({
- type: 'stylesheet',
- options: { 'stylesheet.fuzzySearchMinScore': 0 }
- })), 'align-self: unset;');
- equal(expand('auto', resolveConfig({
- type: 'stylesheet',
- options: { 'stylesheet.fuzzySearchMinScore': 0.3 }
- })), 'auto: ;');
+ it('unmatched abbreviation', () => {
+ // This example is useless: it’s unexpected to receive `align-self: unset`
+ // for `auto` snippet
+ // equal(expand('auto', resolveConfig({
+ // type: 'stylesheet',
+ // options: { 'stylesheet.fuzzySearchMinScore': 0 }
+ // })), 'align-self: unset;');
+ equal(expand('auto'), 'auto: ${0};');
});
it('CSS-in-JS', () => {
@@ -189,4 +190,28 @@ describe('Stylesheet abbreviations', () => {
equal(expand('s', config), 'start');
equal(expand('a', config), 'auto');
});
+
+ it('limit snippets by scope', () => {
+ const sectionScope = resolveConfig({
+ type: 'stylesheet',
+ context: { name: CSSAbbreviationScope.Section },
+ snippets: {
+ mten: 'margin: 10px;',
+ fsz: 'font-size',
+ myCenterAwesome: 'body {\n\tdisplay: grid;\n}'
+ }
+ });
+ const propertyScope = resolveConfig({
+ type: 'stylesheet',
+ context: { name: CSSAbbreviationScope.Property },
+ snippets: {
+ mten: 'margin: 10px;',
+ fsz: 'font-size',
+ myCenterAwesome: 'body {\n\tdisplay: grid;\n}'
+ }
+ });
+
+ equal(expand('m', sectionScope), 'body {\n\tdisplay: grid;\n}');
+ equal(expand('m', propertyScope), 'margin: ;');
+ });
});
| 39 | Updated CSS abbreviation scoring algorithm | 14 | .ts | ts | mit | emmetio/emmet |
10071943 | <NME> experiment.rb
<BEF> # frozen_string_literal: true
attr_accessor :name
attr_accessor :alternative_names
attr_accessor :winner
attr_accessor :version
def initialize(name, *alternative_names)
@name = name.to_s
@alternative_names = alternative_names.map do |alternative|
Split::Alternative.new(alternative, name)
end.map(&:name)
@version = (Split.redis.get("#{name.to_s}:version").to_i || 0)
end
def winner
}
def self.find(name)
Split.cache(:experiments, name) do
return unless Split.redis.exists?(name)
Experiment.new(name).tap { |exp| exp.load_from_redis }
end
end
def initialize(name, options = {})
options = DEFAULT_OPTIONS.merge(options)
Split.redis.hdel(:experiment_winner, name)
end
def winner=(winner_name)
Split.redis.hset(:experiment_winner, name, winner_name.to_s)
end
end
def set_alternatives_and_options(options)
options_with_defaults = DEFAULT_OPTIONS.merge(
options.reject { |k, v| v.nil? }
)
self.alternatives = options_with_defaults[:alternatives]
self.goals = options_with_defaults[:goals]
self.resettable = options_with_defaults[:resettable]
self.algorithm = options_with_defaults[:algorithm]
self.metadata = options_with_defaults[:metadata]
end
def extract_alternatives_from_options(options)
alts = options[:alternatives] || []
if alts.length == 1
if alts[0].is_a? Hash
end
def version
@version ||= 0
end
def increment_version
@version += 1
Split.redis.set("#{name}:version", @version)
end
def key
options[:algorithm] = exp_config[:algorithm]
end
end
options[:alternatives] = alts
set_alternatives_and_options(options)
# calculate probability that each alternative is the winner
@alternative_probabilities = {}
alts
end
def save
validate!
if new_record?
start unless Split.configuration.start_manually
persist_experiment_configuration
elsif experiment_configuration_has_changed?
reset unless Split.configuration.reset_manually
persist_experiment_configuration
end
redis.hmset(experiment_config_key, :resettable, resettable.to_s,
:algorithm, algorithm.to_s)
self
end
def validate!
if @alternatives.empty? && Split.configuration.experiment_for(@name).nil?
raise ExperimentNotFound.new("Experiment #{@name} not found")
end
@alternatives.each { |a| a.validate! }
goals_collection.validate!
end
def new_record?
ExperimentCatalog.find(name).nil?
end
def ==(obj)
self.name == obj.name
end
def [](name)
alternatives.find { |a| a.name == name }
end
def algorithm
@algorithm ||= Split.configuration.algorithm
end
def algorithm=(algorithm)
@algorithm = algorithm.is_a?(String) ? algorithm.constantize : algorithm
end
def resettable=(resettable)
@resettable = resettable.is_a?(String) ? resettable == "true" : resettable
end
def alternatives=(alts)
@alternatives = alts.map do |alternative|
if alternative.kind_of?(Split::Alternative)
alternative
else
Split::Alternative.new(alternative, @name)
end
end
end
def winner
Split.cache(:experiment_winner, name) do
experiment_winner = redis.hget(:experiment_winner, name)
if experiment_winner
Split::Alternative.new(experiment_winner, name)
else
nil
end
end
end
def has_winner?
return @has_winner if defined? @has_winner
@has_winner = !winner.nil?
end
def winner=(winner_name)
redis.hset(:experiment_winner, name, winner_name.to_s)
@has_winner = true
Split.configuration.on_experiment_winner_choose.call(self)
end
def participant_count
alternatives.inject(0) { |sum, a| sum + a.participant_count }
end
def control
alternatives.first
end
def reset_winner
redis.hdel(:experiment_winner, name)
@has_winner = false
Split::Cache.clear_key(@name)
end
def start
redis.hset(:experiment_start_times, @name, Time.now.to_i)
end
def start_time
Split.cache(:experiment_start_times, @name) do
t = redis.hget(:experiment_start_times, @name)
if t
# Check if stored time is an integer
if t =~ /^[-+]?[0-9]+$/
Time.at(t.to_i)
else
Time.parse(t)
end
end
end
end
def next_alternative
winner || random_alternative
end
def random_alternative
if alternatives.length > 1
algorithm.choose_alternative(self)
else
alternatives.first
end
end
def version
@version ||= (redis.get("#{name}:version").to_i || 0)
end
def increment_version
@version = redis.incr("#{name}:version")
end
def key
if version.to_i > 0
"#{name}:#{version}"
else
name
end
end
def goals_key
"#{name}:goals"
end
def finished_key
self.class.finished_key(key)
end
def metadata_key
"#{name}:metadata"
end
def resettable?
resettable
end
def reset
Split.configuration.on_before_experiment_reset.call(self)
Split::Cache.clear_key(@name)
alternatives.each(&:reset)
reset_winner
Split.configuration.on_experiment_reset.call(self)
increment_version
end
def delete
Split.configuration.on_before_experiment_delete.call(self)
if Split.configuration.start_manually
redis.hdel(:experiment_start_times, @name)
end
reset_winner
redis.srem(:experiments, name)
remove_experiment_cohorting
remove_experiment_configuration
Split.configuration.on_experiment_delete.call(self)
increment_version
end
def delete_metadata
redis.del(metadata_key)
end
def load_from_redis
exp_config = redis.hgetall(experiment_config_key)
options = {
resettable: exp_config["resettable"],
algorithm: exp_config["algorithm"],
alternatives: load_alternatives_from_redis,
goals: Split::GoalsCollection.new(@name).load_from_redis,
metadata: load_metadata_from_redis
}
set_alternatives_and_options(options)
end
def calc_winning_alternatives
# Cache the winning alternatives so we recalculate them once per the specified interval.
intervals_since_epoch =
Time.now.utc.to_i / Split.configuration.winning_alternative_recalculation_interval
if self.calc_time != intervals_since_epoch
if goals.empty?
self.estimate_winning_alternative
else
goals.each do |goal|
self.estimate_winning_alternative(goal)
end
end
self.calc_time = intervals_since_epoch
self.save
end
end
def estimate_winning_alternative(goal = nil)
# initialize a hash of beta distributions based on the alternatives' conversion rates
beta_params = calc_beta_params(goal)
winning_alternatives = []
Split.configuration.beta_probability_simulations.times do
# calculate simulated conversion rates from the beta distributions
simulated_cr_hash = calc_simulated_conversion_rates(beta_params)
winning_alternative = find_simulated_winner(simulated_cr_hash)
# push the winning pair to the winning_alternatives array
winning_alternatives.push(winning_alternative)
end
winning_counts = count_simulated_wins(winning_alternatives)
@alternative_probabilities = calc_alternative_probabilities(winning_counts, Split.configuration.beta_probability_simulations)
write_to_alternatives(goal)
self.save
end
def write_to_alternatives(goal = nil)
alternatives.each do |alternative|
alternative.set_p_winner(@alternative_probabilities[alternative], goal)
end
end
def calc_alternative_probabilities(winning_counts, number_of_simulations)
alternative_probabilities = {}
winning_counts.each do |alternative, wins|
alternative_probabilities[alternative] = wins / number_of_simulations.to_f
end
alternative_probabilities
end
def count_simulated_wins(winning_alternatives)
# initialize a hash to keep track of winning alternative in simulations
winning_counts = {}
alternatives.each do |alternative|
winning_counts[alternative] = 0
end
# count number of times each alternative won, calculate probabilities, place in hash
winning_alternatives.each do |alternative|
winning_counts[alternative] += 1
end
winning_counts
end
def find_simulated_winner(simulated_cr_hash)
# figure out which alternative had the highest simulated conversion rate
winning_pair = ["", 0.0]
simulated_cr_hash.each do |alternative, rate|
if rate > winning_pair[1]
winning_pair = [alternative, rate]
end
end
winner = winning_pair[0]
winner
end
def calc_simulated_conversion_rates(beta_params)
simulated_cr_hash = {}
# create a hash which has the conversion rate pulled from each alternative's beta distribution
beta_params.each do |alternative, params|
alpha = params[0]
beta = params[1]
simulated_conversion_rate = Split::Algorithms.beta_distribution_rng(alpha, beta)
simulated_cr_hash[alternative] = simulated_conversion_rate
end
simulated_cr_hash
end
def calc_beta_params(goal = nil)
beta_params = {}
alternatives.each do |alternative|
conversions = goal.nil? ? alternative.completed_count : alternative.completed_count(goal)
alpha = 1 + conversions
beta = 1 + alternative.participant_count - conversions
params = [alpha, beta]
beta_params[alternative] = params
end
beta_params
end
def calc_time=(time)
redis.hset(experiment_config_key, :calc_time, time)
end
def calc_time
redis.hget(experiment_config_key, :calc_time).to_i
end
def jstring(goal = nil)
js_id = if goal.nil?
name
else
name + "-" + goal
end
js_id.gsub("/", "--")
end
def cohorting_disabled?
@cohorting_disabled ||= begin
value = redis.hget(experiment_config_key, :cohorting)
value.nil? ? false : value.downcase == "true"
end
end
def disable_cohorting
@cohorting_disabled = true
redis.hset(experiment_config_key, :cohorting, true.to_s)
end
def enable_cohorting
@cohorting_disabled = false
redis.hset(experiment_config_key, :cohorting, false.to_s)
end
protected
def experiment_config_key
"experiment_configurations/#{@name}"
end
def load_metadata_from_configuration
Split.configuration.experiment_for(@name)[:metadata]
end
def load_metadata_from_redis
meta = redis.get(metadata_key)
JSON.parse(meta) unless meta.nil?
end
def load_alternatives_from_configuration
alts = Split.configuration.experiment_for(@name)[:alternatives]
raise ArgumentError, "Experiment configuration is missing :alternatives array" unless alts
if alts.is_a?(Hash)
alts.keys
else
alts.flatten
end
end
def load_alternatives_from_redis
alternatives = redis.lrange(@name, 0, -1)
alternatives.map do |alt|
alt = begin
JSON.parse(alt)
rescue
alt
end
Split::Alternative.new(alt, @name)
end
end
private
def redis
Split.redis
end
def redis_interface
RedisInterface.new
end
def persist_experiment_configuration
redis_interface.add_to_set(:experiments, name)
redis_interface.persist_list(name, @alternatives.map { |alt| { alt.name => alt.weight }.to_json })
goals_collection.save
if @metadata
redis.set(metadata_key, @metadata.to_json)
else
delete_metadata
end
end
def remove_experiment_configuration
@alternatives.each(&:delete)
goals_collection.delete
delete_metadata
redis.del(@name)
end
def experiment_configuration_has_changed?
existing_experiment = Experiment.find(@name)
existing_experiment.alternatives.map(&:to_s) != @alternatives.map(&:to_s) ||
existing_experiment.goals != @goals ||
existing_experiment.metadata != @metadata
end
def goals_collection
Split::GoalsCollection.new(@name, @goals)
end
def remove_experiment_cohorting
@cohorting_disabled = false
redis.hdel(experiment_config_key, :cohorting)
end
end
end
<MSG> Increment experiment version using redis
<DFF> @@ -3,15 +3,12 @@ module Split
attr_accessor :name
attr_accessor :alternative_names
attr_accessor :winner
- attr_accessor :version
def initialize(name, *alternative_names)
@name = name.to_s
@alternative_names = alternative_names.map do |alternative|
Split::Alternative.new(alternative, name)
end.map(&:name)
-
- @version = (Split.redis.get("#{name.to_s}:version").to_i || 0)
end
def winner
@@ -30,6 +27,7 @@ module Split
Split.redis.hdel(:experiment_winner, name)
end
+
def winner=(winner_name)
Split.redis.hset(:experiment_winner, name, winner_name.to_s)
end
@@ -55,12 +53,11 @@ module Split
end
def version
- @version ||= 0
+ @version ||= (Split.redis.get("#{name.to_s}:version").to_i || 0)
end
def increment_version
- @version += 1
- Split.redis.set("#{name}:version", @version)
+ @version = Split.redis.incr("#{name}:version")
end
def key
| 3 | Increment experiment version using redis | 6 | .rb | rb | mit | splitrb/split |
10071944 | <NME> experiment.rb
<BEF> # frozen_string_literal: true
attr_accessor :name
attr_accessor :alternative_names
attr_accessor :winner
attr_accessor :version
def initialize(name, *alternative_names)
@name = name.to_s
@alternative_names = alternative_names.map do |alternative|
Split::Alternative.new(alternative, name)
end.map(&:name)
@version = (Split.redis.get("#{name.to_s}:version").to_i || 0)
end
def winner
}
def self.find(name)
Split.cache(:experiments, name) do
return unless Split.redis.exists?(name)
Experiment.new(name).tap { |exp| exp.load_from_redis }
end
end
def initialize(name, options = {})
options = DEFAULT_OPTIONS.merge(options)
Split.redis.hdel(:experiment_winner, name)
end
def winner=(winner_name)
Split.redis.hset(:experiment_winner, name, winner_name.to_s)
end
end
def set_alternatives_and_options(options)
options_with_defaults = DEFAULT_OPTIONS.merge(
options.reject { |k, v| v.nil? }
)
self.alternatives = options_with_defaults[:alternatives]
self.goals = options_with_defaults[:goals]
self.resettable = options_with_defaults[:resettable]
self.algorithm = options_with_defaults[:algorithm]
self.metadata = options_with_defaults[:metadata]
end
def extract_alternatives_from_options(options)
alts = options[:alternatives] || []
if alts.length == 1
if alts[0].is_a? Hash
end
def version
@version ||= 0
end
def increment_version
@version += 1
Split.redis.set("#{name}:version", @version)
end
def key
options[:algorithm] = exp_config[:algorithm]
end
end
options[:alternatives] = alts
set_alternatives_and_options(options)
# calculate probability that each alternative is the winner
@alternative_probabilities = {}
alts
end
def save
validate!
if new_record?
start unless Split.configuration.start_manually
persist_experiment_configuration
elsif experiment_configuration_has_changed?
reset unless Split.configuration.reset_manually
persist_experiment_configuration
end
redis.hmset(experiment_config_key, :resettable, resettable.to_s,
:algorithm, algorithm.to_s)
self
end
def validate!
if @alternatives.empty? && Split.configuration.experiment_for(@name).nil?
raise ExperimentNotFound.new("Experiment #{@name} not found")
end
@alternatives.each { |a| a.validate! }
goals_collection.validate!
end
def new_record?
ExperimentCatalog.find(name).nil?
end
def ==(obj)
self.name == obj.name
end
def [](name)
alternatives.find { |a| a.name == name }
end
def algorithm
@algorithm ||= Split.configuration.algorithm
end
def algorithm=(algorithm)
@algorithm = algorithm.is_a?(String) ? algorithm.constantize : algorithm
end
def resettable=(resettable)
@resettable = resettable.is_a?(String) ? resettable == "true" : resettable
end
def alternatives=(alts)
@alternatives = alts.map do |alternative|
if alternative.kind_of?(Split::Alternative)
alternative
else
Split::Alternative.new(alternative, @name)
end
end
end
def winner
Split.cache(:experiment_winner, name) do
experiment_winner = redis.hget(:experiment_winner, name)
if experiment_winner
Split::Alternative.new(experiment_winner, name)
else
nil
end
end
end
def has_winner?
return @has_winner if defined? @has_winner
@has_winner = !winner.nil?
end
def winner=(winner_name)
redis.hset(:experiment_winner, name, winner_name.to_s)
@has_winner = true
Split.configuration.on_experiment_winner_choose.call(self)
end
def participant_count
alternatives.inject(0) { |sum, a| sum + a.participant_count }
end
def control
alternatives.first
end
def reset_winner
redis.hdel(:experiment_winner, name)
@has_winner = false
Split::Cache.clear_key(@name)
end
def start
redis.hset(:experiment_start_times, @name, Time.now.to_i)
end
def start_time
Split.cache(:experiment_start_times, @name) do
t = redis.hget(:experiment_start_times, @name)
if t
# Check if stored time is an integer
if t =~ /^[-+]?[0-9]+$/
Time.at(t.to_i)
else
Time.parse(t)
end
end
end
end
def next_alternative
winner || random_alternative
end
def random_alternative
if alternatives.length > 1
algorithm.choose_alternative(self)
else
alternatives.first
end
end
def version
@version ||= (redis.get("#{name}:version").to_i || 0)
end
def increment_version
@version = redis.incr("#{name}:version")
end
def key
if version.to_i > 0
"#{name}:#{version}"
else
name
end
end
def goals_key
"#{name}:goals"
end
def finished_key
self.class.finished_key(key)
end
def metadata_key
"#{name}:metadata"
end
def resettable?
resettable
end
def reset
Split.configuration.on_before_experiment_reset.call(self)
Split::Cache.clear_key(@name)
alternatives.each(&:reset)
reset_winner
Split.configuration.on_experiment_reset.call(self)
increment_version
end
def delete
Split.configuration.on_before_experiment_delete.call(self)
if Split.configuration.start_manually
redis.hdel(:experiment_start_times, @name)
end
reset_winner
redis.srem(:experiments, name)
remove_experiment_cohorting
remove_experiment_configuration
Split.configuration.on_experiment_delete.call(self)
increment_version
end
def delete_metadata
redis.del(metadata_key)
end
def load_from_redis
exp_config = redis.hgetall(experiment_config_key)
options = {
resettable: exp_config["resettable"],
algorithm: exp_config["algorithm"],
alternatives: load_alternatives_from_redis,
goals: Split::GoalsCollection.new(@name).load_from_redis,
metadata: load_metadata_from_redis
}
set_alternatives_and_options(options)
end
def calc_winning_alternatives
# Cache the winning alternatives so we recalculate them once per the specified interval.
intervals_since_epoch =
Time.now.utc.to_i / Split.configuration.winning_alternative_recalculation_interval
if self.calc_time != intervals_since_epoch
if goals.empty?
self.estimate_winning_alternative
else
goals.each do |goal|
self.estimate_winning_alternative(goal)
end
end
self.calc_time = intervals_since_epoch
self.save
end
end
def estimate_winning_alternative(goal = nil)
# initialize a hash of beta distributions based on the alternatives' conversion rates
beta_params = calc_beta_params(goal)
winning_alternatives = []
Split.configuration.beta_probability_simulations.times do
# calculate simulated conversion rates from the beta distributions
simulated_cr_hash = calc_simulated_conversion_rates(beta_params)
winning_alternative = find_simulated_winner(simulated_cr_hash)
# push the winning pair to the winning_alternatives array
winning_alternatives.push(winning_alternative)
end
winning_counts = count_simulated_wins(winning_alternatives)
@alternative_probabilities = calc_alternative_probabilities(winning_counts, Split.configuration.beta_probability_simulations)
write_to_alternatives(goal)
self.save
end
def write_to_alternatives(goal = nil)
alternatives.each do |alternative|
alternative.set_p_winner(@alternative_probabilities[alternative], goal)
end
end
def calc_alternative_probabilities(winning_counts, number_of_simulations)
alternative_probabilities = {}
winning_counts.each do |alternative, wins|
alternative_probabilities[alternative] = wins / number_of_simulations.to_f
end
alternative_probabilities
end
def count_simulated_wins(winning_alternatives)
# initialize a hash to keep track of winning alternative in simulations
winning_counts = {}
alternatives.each do |alternative|
winning_counts[alternative] = 0
end
# count number of times each alternative won, calculate probabilities, place in hash
winning_alternatives.each do |alternative|
winning_counts[alternative] += 1
end
winning_counts
end
def find_simulated_winner(simulated_cr_hash)
# figure out which alternative had the highest simulated conversion rate
winning_pair = ["", 0.0]
simulated_cr_hash.each do |alternative, rate|
if rate > winning_pair[1]
winning_pair = [alternative, rate]
end
end
winner = winning_pair[0]
winner
end
def calc_simulated_conversion_rates(beta_params)
simulated_cr_hash = {}
# create a hash which has the conversion rate pulled from each alternative's beta distribution
beta_params.each do |alternative, params|
alpha = params[0]
beta = params[1]
simulated_conversion_rate = Split::Algorithms.beta_distribution_rng(alpha, beta)
simulated_cr_hash[alternative] = simulated_conversion_rate
end
simulated_cr_hash
end
def calc_beta_params(goal = nil)
beta_params = {}
alternatives.each do |alternative|
conversions = goal.nil? ? alternative.completed_count : alternative.completed_count(goal)
alpha = 1 + conversions
beta = 1 + alternative.participant_count - conversions
params = [alpha, beta]
beta_params[alternative] = params
end
beta_params
end
def calc_time=(time)
redis.hset(experiment_config_key, :calc_time, time)
end
def calc_time
redis.hget(experiment_config_key, :calc_time).to_i
end
def jstring(goal = nil)
js_id = if goal.nil?
name
else
name + "-" + goal
end
js_id.gsub("/", "--")
end
def cohorting_disabled?
@cohorting_disabled ||= begin
value = redis.hget(experiment_config_key, :cohorting)
value.nil? ? false : value.downcase == "true"
end
end
def disable_cohorting
@cohorting_disabled = true
redis.hset(experiment_config_key, :cohorting, true.to_s)
end
def enable_cohorting
@cohorting_disabled = false
redis.hset(experiment_config_key, :cohorting, false.to_s)
end
protected
def experiment_config_key
"experiment_configurations/#{@name}"
end
def load_metadata_from_configuration
Split.configuration.experiment_for(@name)[:metadata]
end
def load_metadata_from_redis
meta = redis.get(metadata_key)
JSON.parse(meta) unless meta.nil?
end
def load_alternatives_from_configuration
alts = Split.configuration.experiment_for(@name)[:alternatives]
raise ArgumentError, "Experiment configuration is missing :alternatives array" unless alts
if alts.is_a?(Hash)
alts.keys
else
alts.flatten
end
end
def load_alternatives_from_redis
alternatives = redis.lrange(@name, 0, -1)
alternatives.map do |alt|
alt = begin
JSON.parse(alt)
rescue
alt
end
Split::Alternative.new(alt, @name)
end
end
private
def redis
Split.redis
end
def redis_interface
RedisInterface.new
end
def persist_experiment_configuration
redis_interface.add_to_set(:experiments, name)
redis_interface.persist_list(name, @alternatives.map { |alt| { alt.name => alt.weight }.to_json })
goals_collection.save
if @metadata
redis.set(metadata_key, @metadata.to_json)
else
delete_metadata
end
end
def remove_experiment_configuration
@alternatives.each(&:delete)
goals_collection.delete
delete_metadata
redis.del(@name)
end
def experiment_configuration_has_changed?
existing_experiment = Experiment.find(@name)
existing_experiment.alternatives.map(&:to_s) != @alternatives.map(&:to_s) ||
existing_experiment.goals != @goals ||
existing_experiment.metadata != @metadata
end
def goals_collection
Split::GoalsCollection.new(@name, @goals)
end
def remove_experiment_cohorting
@cohorting_disabled = false
redis.hdel(experiment_config_key, :cohorting)
end
end
end
<MSG> Increment experiment version using redis
<DFF> @@ -3,15 +3,12 @@ module Split
attr_accessor :name
attr_accessor :alternative_names
attr_accessor :winner
- attr_accessor :version
def initialize(name, *alternative_names)
@name = name.to_s
@alternative_names = alternative_names.map do |alternative|
Split::Alternative.new(alternative, name)
end.map(&:name)
-
- @version = (Split.redis.get("#{name.to_s}:version").to_i || 0)
end
def winner
@@ -30,6 +27,7 @@ module Split
Split.redis.hdel(:experiment_winner, name)
end
+
def winner=(winner_name)
Split.redis.hset(:experiment_winner, name, winner_name.to_s)
end
@@ -55,12 +53,11 @@ module Split
end
def version
- @version ||= 0
+ @version ||= (Split.redis.get("#{name.to_s}:version").to_i || 0)
end
def increment_version
- @version += 1
- Split.redis.set("#{name}:version", @version)
+ @version = Split.redis.incr("#{name}:version")
end
def key
| 3 | Increment experiment version using redis | 6 | .rb | rb | mit | splitrb/split |
10071945 | <NME> experiment.rb
<BEF> # frozen_string_literal: true
attr_accessor :name
attr_accessor :alternative_names
attr_accessor :winner
attr_accessor :version
def initialize(name, *alternative_names)
@name = name.to_s
@alternative_names = alternative_names.map do |alternative|
Split::Alternative.new(alternative, name)
end.map(&:name)
@version = (Split.redis.get("#{name.to_s}:version").to_i || 0)
end
def winner
}
def self.find(name)
Split.cache(:experiments, name) do
return unless Split.redis.exists?(name)
Experiment.new(name).tap { |exp| exp.load_from_redis }
end
end
def initialize(name, options = {})
options = DEFAULT_OPTIONS.merge(options)
Split.redis.hdel(:experiment_winner, name)
end
def winner=(winner_name)
Split.redis.hset(:experiment_winner, name, winner_name.to_s)
end
end
def set_alternatives_and_options(options)
options_with_defaults = DEFAULT_OPTIONS.merge(
options.reject { |k, v| v.nil? }
)
self.alternatives = options_with_defaults[:alternatives]
self.goals = options_with_defaults[:goals]
self.resettable = options_with_defaults[:resettable]
self.algorithm = options_with_defaults[:algorithm]
self.metadata = options_with_defaults[:metadata]
end
def extract_alternatives_from_options(options)
alts = options[:alternatives] || []
if alts.length == 1
if alts[0].is_a? Hash
end
def version
@version ||= 0
end
def increment_version
@version += 1
Split.redis.set("#{name}:version", @version)
end
def key
options[:algorithm] = exp_config[:algorithm]
end
end
options[:alternatives] = alts
set_alternatives_and_options(options)
# calculate probability that each alternative is the winner
@alternative_probabilities = {}
alts
end
def save
validate!
if new_record?
start unless Split.configuration.start_manually
persist_experiment_configuration
elsif experiment_configuration_has_changed?
reset unless Split.configuration.reset_manually
persist_experiment_configuration
end
redis.hmset(experiment_config_key, :resettable, resettable.to_s,
:algorithm, algorithm.to_s)
self
end
def validate!
if @alternatives.empty? && Split.configuration.experiment_for(@name).nil?
raise ExperimentNotFound.new("Experiment #{@name} not found")
end
@alternatives.each { |a| a.validate! }
goals_collection.validate!
end
def new_record?
ExperimentCatalog.find(name).nil?
end
def ==(obj)
self.name == obj.name
end
def [](name)
alternatives.find { |a| a.name == name }
end
def algorithm
@algorithm ||= Split.configuration.algorithm
end
def algorithm=(algorithm)
@algorithm = algorithm.is_a?(String) ? algorithm.constantize : algorithm
end
def resettable=(resettable)
@resettable = resettable.is_a?(String) ? resettable == "true" : resettable
end
def alternatives=(alts)
@alternatives = alts.map do |alternative|
if alternative.kind_of?(Split::Alternative)
alternative
else
Split::Alternative.new(alternative, @name)
end
end
end
def winner
Split.cache(:experiment_winner, name) do
experiment_winner = redis.hget(:experiment_winner, name)
if experiment_winner
Split::Alternative.new(experiment_winner, name)
else
nil
end
end
end
def has_winner?
return @has_winner if defined? @has_winner
@has_winner = !winner.nil?
end
def winner=(winner_name)
redis.hset(:experiment_winner, name, winner_name.to_s)
@has_winner = true
Split.configuration.on_experiment_winner_choose.call(self)
end
def participant_count
alternatives.inject(0) { |sum, a| sum + a.participant_count }
end
def control
alternatives.first
end
def reset_winner
redis.hdel(:experiment_winner, name)
@has_winner = false
Split::Cache.clear_key(@name)
end
def start
redis.hset(:experiment_start_times, @name, Time.now.to_i)
end
def start_time
Split.cache(:experiment_start_times, @name) do
t = redis.hget(:experiment_start_times, @name)
if t
# Check if stored time is an integer
if t =~ /^[-+]?[0-9]+$/
Time.at(t.to_i)
else
Time.parse(t)
end
end
end
end
def next_alternative
winner || random_alternative
end
def random_alternative
if alternatives.length > 1
algorithm.choose_alternative(self)
else
alternatives.first
end
end
def version
@version ||= (redis.get("#{name}:version").to_i || 0)
end
def increment_version
@version = redis.incr("#{name}:version")
end
def key
if version.to_i > 0
"#{name}:#{version}"
else
name
end
end
def goals_key
"#{name}:goals"
end
def finished_key
self.class.finished_key(key)
end
def metadata_key
"#{name}:metadata"
end
def resettable?
resettable
end
def reset
Split.configuration.on_before_experiment_reset.call(self)
Split::Cache.clear_key(@name)
alternatives.each(&:reset)
reset_winner
Split.configuration.on_experiment_reset.call(self)
increment_version
end
def delete
Split.configuration.on_before_experiment_delete.call(self)
if Split.configuration.start_manually
redis.hdel(:experiment_start_times, @name)
end
reset_winner
redis.srem(:experiments, name)
remove_experiment_cohorting
remove_experiment_configuration
Split.configuration.on_experiment_delete.call(self)
increment_version
end
def delete_metadata
redis.del(metadata_key)
end
def load_from_redis
exp_config = redis.hgetall(experiment_config_key)
options = {
resettable: exp_config["resettable"],
algorithm: exp_config["algorithm"],
alternatives: load_alternatives_from_redis,
goals: Split::GoalsCollection.new(@name).load_from_redis,
metadata: load_metadata_from_redis
}
set_alternatives_and_options(options)
end
def calc_winning_alternatives
# Cache the winning alternatives so we recalculate them once per the specified interval.
intervals_since_epoch =
Time.now.utc.to_i / Split.configuration.winning_alternative_recalculation_interval
if self.calc_time != intervals_since_epoch
if goals.empty?
self.estimate_winning_alternative
else
goals.each do |goal|
self.estimate_winning_alternative(goal)
end
end
self.calc_time = intervals_since_epoch
self.save
end
end
def estimate_winning_alternative(goal = nil)
# initialize a hash of beta distributions based on the alternatives' conversion rates
beta_params = calc_beta_params(goal)
winning_alternatives = []
Split.configuration.beta_probability_simulations.times do
# calculate simulated conversion rates from the beta distributions
simulated_cr_hash = calc_simulated_conversion_rates(beta_params)
winning_alternative = find_simulated_winner(simulated_cr_hash)
# push the winning pair to the winning_alternatives array
winning_alternatives.push(winning_alternative)
end
winning_counts = count_simulated_wins(winning_alternatives)
@alternative_probabilities = calc_alternative_probabilities(winning_counts, Split.configuration.beta_probability_simulations)
write_to_alternatives(goal)
self.save
end
def write_to_alternatives(goal = nil)
alternatives.each do |alternative|
alternative.set_p_winner(@alternative_probabilities[alternative], goal)
end
end
def calc_alternative_probabilities(winning_counts, number_of_simulations)
alternative_probabilities = {}
winning_counts.each do |alternative, wins|
alternative_probabilities[alternative] = wins / number_of_simulations.to_f
end
alternative_probabilities
end
def count_simulated_wins(winning_alternatives)
# initialize a hash to keep track of winning alternative in simulations
winning_counts = {}
alternatives.each do |alternative|
winning_counts[alternative] = 0
end
# count number of times each alternative won, calculate probabilities, place in hash
winning_alternatives.each do |alternative|
winning_counts[alternative] += 1
end
winning_counts
end
def find_simulated_winner(simulated_cr_hash)
# figure out which alternative had the highest simulated conversion rate
winning_pair = ["", 0.0]
simulated_cr_hash.each do |alternative, rate|
if rate > winning_pair[1]
winning_pair = [alternative, rate]
end
end
winner = winning_pair[0]
winner
end
def calc_simulated_conversion_rates(beta_params)
simulated_cr_hash = {}
# create a hash which has the conversion rate pulled from each alternative's beta distribution
beta_params.each do |alternative, params|
alpha = params[0]
beta = params[1]
simulated_conversion_rate = Split::Algorithms.beta_distribution_rng(alpha, beta)
simulated_cr_hash[alternative] = simulated_conversion_rate
end
simulated_cr_hash
end
def calc_beta_params(goal = nil)
beta_params = {}
alternatives.each do |alternative|
conversions = goal.nil? ? alternative.completed_count : alternative.completed_count(goal)
alpha = 1 + conversions
beta = 1 + alternative.participant_count - conversions
params = [alpha, beta]
beta_params[alternative] = params
end
beta_params
end
def calc_time=(time)
redis.hset(experiment_config_key, :calc_time, time)
end
def calc_time
redis.hget(experiment_config_key, :calc_time).to_i
end
def jstring(goal = nil)
js_id = if goal.nil?
name
else
name + "-" + goal
end
js_id.gsub("/", "--")
end
def cohorting_disabled?
@cohorting_disabled ||= begin
value = redis.hget(experiment_config_key, :cohorting)
value.nil? ? false : value.downcase == "true"
end
end
def disable_cohorting
@cohorting_disabled = true
redis.hset(experiment_config_key, :cohorting, true.to_s)
end
def enable_cohorting
@cohorting_disabled = false
redis.hset(experiment_config_key, :cohorting, false.to_s)
end
protected
def experiment_config_key
"experiment_configurations/#{@name}"
end
def load_metadata_from_configuration
Split.configuration.experiment_for(@name)[:metadata]
end
def load_metadata_from_redis
meta = redis.get(metadata_key)
JSON.parse(meta) unless meta.nil?
end
def load_alternatives_from_configuration
alts = Split.configuration.experiment_for(@name)[:alternatives]
raise ArgumentError, "Experiment configuration is missing :alternatives array" unless alts
if alts.is_a?(Hash)
alts.keys
else
alts.flatten
end
end
def load_alternatives_from_redis
alternatives = redis.lrange(@name, 0, -1)
alternatives.map do |alt|
alt = begin
JSON.parse(alt)
rescue
alt
end
Split::Alternative.new(alt, @name)
end
end
private
def redis
Split.redis
end
def redis_interface
RedisInterface.new
end
def persist_experiment_configuration
redis_interface.add_to_set(:experiments, name)
redis_interface.persist_list(name, @alternatives.map { |alt| { alt.name => alt.weight }.to_json })
goals_collection.save
if @metadata
redis.set(metadata_key, @metadata.to_json)
else
delete_metadata
end
end
def remove_experiment_configuration
@alternatives.each(&:delete)
goals_collection.delete
delete_metadata
redis.del(@name)
end
def experiment_configuration_has_changed?
existing_experiment = Experiment.find(@name)
existing_experiment.alternatives.map(&:to_s) != @alternatives.map(&:to_s) ||
existing_experiment.goals != @goals ||
existing_experiment.metadata != @metadata
end
def goals_collection
Split::GoalsCollection.new(@name, @goals)
end
def remove_experiment_cohorting
@cohorting_disabled = false
redis.hdel(experiment_config_key, :cohorting)
end
end
end
<MSG> Increment experiment version using redis
<DFF> @@ -3,15 +3,12 @@ module Split
attr_accessor :name
attr_accessor :alternative_names
attr_accessor :winner
- attr_accessor :version
def initialize(name, *alternative_names)
@name = name.to_s
@alternative_names = alternative_names.map do |alternative|
Split::Alternative.new(alternative, name)
end.map(&:name)
-
- @version = (Split.redis.get("#{name.to_s}:version").to_i || 0)
end
def winner
@@ -30,6 +27,7 @@ module Split
Split.redis.hdel(:experiment_winner, name)
end
+
def winner=(winner_name)
Split.redis.hset(:experiment_winner, name, winner_name.to_s)
end
@@ -55,12 +53,11 @@ module Split
end
def version
- @version ||= 0
+ @version ||= (Split.redis.get("#{name.to_s}:version").to_i || 0)
end
def increment_version
- @version += 1
- Split.redis.set("#{name}:version", @version)
+ @version = Split.redis.incr("#{name}:version")
end
def key
| 3 | Increment experiment version using redis | 6 | .rb | rb | mit | splitrb/split |
10071946 | <NME> helper_spec.rb
<BEF> # frozen_string_literal: true
require "spec_helper"
# TODO change some of these tests to use Rack::Test
describe Split::Helper do
include Split::Helper
let(:experiment) {
Split::ExperimentCatalog.find_or_create("link_color", "blue", "red")
}
describe "ab_test" do
it "should not raise an error when passed strings for alternatives" do
expect { ab_test("xyz", "1", "2", "3") }.not_to raise_error
end
it "should not raise an error when passed an array for alternatives" do
expect { ab_test("xyz", ["1", "2", "3"]) }.not_to raise_error
end
it "should raise the appropriate error when passed integers for alternatives" do
expect { ab_test("xyz", 1, 2, 3) }.to raise_error(ArgumentError)
end
it "should raise the appropriate error when passed symbols for alternatives" do
expect { ab_test("xyz", :a, :b, :c) }.to raise_error(ArgumentError)
end
it "should not raise error when passed an array for goals" do
expect { ab_test({ "link_color" => ["purchase", "refund"] }, "blue", "red") }.not_to raise_error
end
it "should not raise error when passed just one goal" do
expect { ab_test({ "link_color" => "purchase" }, "blue", "red") }.not_to raise_error
end
it "raises an appropriate error when processing combined expirements" do
Split.configuration.experiments = {
combined_exp_1: {
alternatives: [ { name: "control", percent: 50 }, { name: "test-alt", percent: 50 } ],
metric: :my_metric,
combined_experiments: [:combined_exp_1_sub_1]
}
}
Split::ExperimentCatalog.find_or_create("combined_exp_1")
expect { ab_test("combined_exp_1") }.to raise_error(Split::InvalidExperimentsFormatError)
end
it "should assign a random alternative to a new user when there are an equal number of alternatives assigned" do
ab_test("link_color", "blue", "red")
expect(["red", "blue"]).to include(ab_user["link_color"])
end
it "should increment the participation counter after assignment to a new user" do
previous_red_count = Split::Alternative.new("red", "link_color").participant_count
previous_blue_count = Split::Alternative.new("blue", "link_color").participant_count
ab_test("link_color", "blue", "red")
new_red_count = Split::Alternative.new("red", "link_color").participant_count
new_blue_count = Split::Alternative.new("blue", "link_color").participant_count
expect((new_red_count + new_blue_count)).to eq(previous_red_count + previous_blue_count + 1)
end
it "should not increment the counter for an experiment that the user is not participating in" do
ab_test("link_color", "blue", "red")
e = Split::ExperimentCatalog.find_or_create("button_size", "small", "big")
expect {
# User shouldn't participate in this second experiment
ab_test("button_size", "small", "big")
}.not_to change { e.participant_count }
end
it "should not increment the counter for an ended experiment" do
e = Split::ExperimentCatalog.find_or_create("button_size", "small", "big")
e.winner = "small"
expect {
a = ab_test("button_size", "small", "big")
expect(a).to eq("small")
}.not_to change { e.participant_count }
end
it "should not increment the counter for an not started experiment" do
expect(Split.configuration).to receive(:start_manually).and_return(true)
e = Split::ExperimentCatalog.find_or_create("button_size", "small", "big")
expect {
a = ab_test("button_size", "small", "big")
expect(a).to eq("small")
}.not_to change { e.participant_count }
end
it "should return the given alternative for an existing user" do
expect(ab_test("link_color", "blue", "red")).to eq ab_test("link_color", "blue", "red")
end
it "should always return the winner if one is present" do
experiment.winner = "orange"
expect(ab_test("link_color", "blue", "red")).to eq("orange")
end
it "should allow the alternative to be forced by passing it in the params" do
# ?ab_test[link_color]=blue
@params = { "ab_test" => { "link_color" => "blue" } }
alternative = ab_test("link_color", "blue", "red")
expect(alternative).to eq("blue")
alternative = ab_test("link_color", { "blue" => 1 }, "red" => 5)
ab_test('link_color', 'blue', 'red')
end
context "when store_override is set" do
before { Split.configuration.store_override = true }
@params = { "SPLIT_DISABLE" => "true" }
alternative = ab_test("link_color", "blue", "red")
expect(alternative).to eq("blue")
alternative = ab_test("link_color", { "blue" => 1 }, "red" => 5)
expect(alternative).to eq("blue")
alternative = ab_test("link_color", "red", "blue")
expect(alternative).to eq("red")
alternative = ab_test("link_color", { "red" => 5 }, "blue" => 1)
expect(alternative).to eq("red")
end
it "should not store the split when Split generically disabled" do
@params = { "SPLIT_DISABLE" => "true" }
expect(ab_user).not_to receive(:[]=)
ab_test("link_color", "blue", "red")
end
context "when store_override is set" do
before { Split.configuration.store_override = true }
it "should store the forced alternative" do
@params = { "ab_test" => { "link_color" => "blue" } }
expect(ab_user).to receive(:[]=).with("link_color", "blue")
ab_test("link_color", "blue", "red")
end
end
context "when on_trial_choose is set" do
before { Split.configuration.on_trial_choose = :some_method }
it "should call the method" do
expect(self).to receive(:some_method)
ab_test("link_color", "blue", "red")
end
end
it "should allow passing a block" do
alt = ab_test("link_color", "blue", "red")
ret = ab_test("link_color", "blue", "red") { |alternative| "shared/#{alternative}" }
expect(ret).to eq("shared/#{alt}")
end
it "should allow the share of visitors see an alternative to be specified" do
ab_test("link_color", { "blue" => 0.8 }, { "red" => 20 })
expect(["red", "blue"]).to include(ab_user["link_color"])
end
it "should allow alternative weighting interface as a single hash" do
ab_test("link_color", { "blue" => 0.01 }, "red" => 0.2)
experiment = Split::ExperimentCatalog.find("link_color")
expect(experiment.alternatives.map(&:name)).to eq(["blue", "red"])
expect(experiment.alternatives.collect { |a| a.weight }).to match_array([0.01, 0.2])
end
it "should only let a user participate in one experiment at a time" do
link_color = ab_test("link_color", "blue", "red")
ab_test("button_size", "small", "big")
expect(ab_user["link_color"]).to eq(link_color)
big = Split::Alternative.new("big", "button_size")
expect(big.participant_count).to eq(0)
small = Split::Alternative.new("small", "button_size")
expect(small.participant_count).to eq(0)
end
it "should let a user participate in many experiment with allow_multiple_experiments option" do
Split.configure do |config|
config.allow_multiple_experiments = true
end
link_color = ab_test("link_color", "blue", "red")
button_size = ab_test("button_size", "small", "big")
expect(ab_user["link_color"]).to eq(link_color)
expect(ab_user["button_size"]).to eq(button_size)
button_size_alt = Split::Alternative.new(button_size, "button_size")
expect(button_size_alt.participant_count).to eq(1)
end
context "with allow_multiple_experiments = 'control'" do
it "should let a user participate in many experiment with one non-'control' alternative" do
Split.configure do |config|
config.allow_multiple_experiments = "control"
end
groups = 100.times.map do |n|
ab_test("test#{n}".to_sym, { "control" => (100 - n) }, { "test#{n}-alt" => n })
end
experiments = ab_user.active_experiments
expect(experiments.size).to be > 1
count_control = experiments.values.count { |g| g == "control" }
expect(count_control).to eq(experiments.size - 1)
count_alts = groups.count { |g| g != "control" }
expect(count_alts).to eq(1)
end
context "when user already has experiment" do
let(:mock_user) { Split::User.new(self, { "test_0" => "test-alt" }) }
before do
Split.configure do |config|
config.allow_multiple_experiments = "control"
end
Split::ExperimentCatalog.find_or_initialize("test_0", "control", "test-alt").save
Split::ExperimentCatalog.find_or_initialize("test_1", "control", "test-alt").save
end
it "should restore previously selected alternative" do
expect(ab_user.active_experiments.size).to eq 1
expect(ab_test(:test_0, { "control" => 100 }, { "test-alt" => 1 })).to eq "test-alt"
expect(ab_test(:test_0, { "control" => 1 }, { "test-alt" => 100 })).to eq "test-alt"
end
it "should select the correct alternatives after experiment resets" do
experiment = Split::ExperimentCatalog.find(:test_0)
experiment.reset
mock_user[experiment.key] = "test-alt"
expect(ab_user.active_experiments.size).to eq 1
expect(ab_test(:test_0, { "control" => 100 }, { "test-alt" => 1 })).to eq "test-alt"
expect(ab_test(:test_0, { "control" => 0 }, { "test-alt" => 100 })).to eq "test-alt"
end
it "lets override existing choice" do
pending "this requires user store reset on first call not depending on whelther it is current trial"
@params = { "ab_test" => { "test_1" => "test-alt" } }
expect(ab_test(:test_0, { "control" => 0 }, { "test-alt" => 100 })).to eq "control"
expect(ab_test(:test_1, { "control" => 100 }, { "test-alt" => 1 })).to eq "test-alt"
end
end
end
it "should not over-write a finished key when an experiment is on a later version" do
experiment.increment_version
ab_user = { experiment.key => "blue", experiment.finished_key => true }
finished_session = ab_user.dup
ab_test("link_color", "blue", "red")
expect(ab_user).to eq(finished_session)
end
end
describe "metadata" do
context "is defined" do
before do
Split.configuration.experiments = {
my_experiment: {
alternatives: ["one", "two"],
resettable: false,
metadata: { "one" => "Meta1", "two" => "Meta2" }
}
}
end
it "should be passed to helper block" do
@params = { "ab_test" => { "my_experiment" => "two" } }
expect(ab_test("my_experiment")).to eq "two"
expect(ab_test("my_experiment") do |alternative, meta|
meta
end).to eq("Meta2")
end
it "should pass control metadata helper block if library disabled" do
Split.configure do |config|
config.enabled = false
end
expect(ab_test("my_experiment")).to eq "one"
expect(ab_test("my_experiment") do |_, meta|
meta
end).to eq("Meta1")
end
end
context "is not defined" do
before do
Split.configuration.experiments = {
my_experiment: {
alternatives: ["one", "two"],
resettable: false,
metadata: nil
}
}
end
it "should be passed to helper block" do
expect(ab_test("my_experiment") do |alternative, meta|
meta
end).to eq({})
end
it "should pass control metadata helper block if library disabled" do
Split.configure do |config|
config.enabled = false
end
expect(ab_test("my_experiment") do |_, meta|
meta
end).to eq({})
end
end
end
describe "ab_finished" do
context "for an experiment that the user participates in" do
before(:each) do
@experiment_name = "link_color"
@alternatives = ["blue", "red"]
@experiment = Split::ExperimentCatalog.find_or_create(@experiment_name, *@alternatives)
@alternative_name = ab_test(@experiment_name, *@alternatives)
@previous_completion_count = Split::Alternative.new(@alternative_name, @experiment_name).completed_count
end
it "should increment the counter for the completed alternative" do
ab_finished(@experiment_name)
new_completion_count = Split::Alternative.new(@alternative_name, @experiment_name).completed_count
expect(new_completion_count).to eq(@previous_completion_count + 1)
end
it "should set experiment's finished key if reset is false" do
ab_finished(@experiment_name, { reset: false })
expect(ab_user[@experiment.key]).to eq(@alternative_name)
expect(ab_user[@experiment.finished_key]).to eq(true)
end
it "should not increment the counter if reset is false and the experiment has been already finished" do
2.times { ab_finished(@experiment_name, { reset: false }) }
new_completion_count = Split::Alternative.new(@alternative_name, @experiment_name).completed_count
expect(new_completion_count).to eq(@previous_completion_count + 1)
end
it "should not increment the counter for an ended experiment" do
e = Split::ExperimentCatalog.find_or_create("button_size", "small", "big")
e.winner = "small"
a = ab_test("button_size", "small", "big")
expect(a).to eq("small")
expect {
ab_finished("button_size")
}.not_to change { Split::Alternative.new(a, "button_size").completed_count }
end
it "should clear out the user's participation from their session" do
expect(ab_user[@experiment.key]).to eq(@alternative_name)
ab_finished(@experiment_name)
expect(ab_user.keys).to be_empty
end
it "should not clear out the users session if reset is false" do
expect(ab_user[@experiment.key]).to eq(@alternative_name)
ab_finished(@experiment_name, { reset: false })
expect(ab_user[@experiment.key]).to eq(@alternative_name)
expect(ab_user[@experiment.finished_key]).to eq(true)
end
it "should reset the users session when experiment is not versioned" do
expect(ab_user[@experiment.key]).to eq(@alternative_name)
ab_finished(@experiment_name)
expect(ab_user.keys).to be_empty
end
it "should reset the users session when experiment is versioned" do
@experiment.increment_version
@alternative_name = ab_test(@experiment_name, *@alternatives)
expect(ab_user[@experiment.key]).to eq(@alternative_name)
ab_finished(@experiment_name)
expect(ab_user.keys).to be_empty
end
context "when on_trial_complete is set" do
before { Split.configuration.on_trial_complete = :some_method }
it "should call the method" do
expect(self).to receive(:some_method)
ab_finished(@experiment_name)
end
it "should not call the method without alternative" do
ab_user[@experiment.key] = nil
expect(self).not_to receive(:some_method)
ab_finished(@experiment_name)
end
end
end
context "for an experiment that the user is excluded from" do
before do
alternative = ab_test("link_color", "blue", "red")
expect(Split::Alternative.new(alternative, "link_color").participant_count).to eq(1)
alternative = ab_test("button_size", "small", "big")
expect(Split::Alternative.new(alternative, "button_size").participant_count).to eq(0)
end
it "should not increment the completed counter" do
# So, user should be participating in the link_color experiment and
# receive the control for button_size. As the user is not participating in
# the button size experiment, finishing it should not increase the
# completion count for that alternative.
expect {
ab_finished("button_size")
}.not_to change { Split::Alternative.new("small", "button_size").completed_count }
end
end
context "for an experiment that the user does not participate in" do
before do
Split::ExperimentCatalog.find_or_create(:not_started_experiment, "control", "alt")
end
it "should not raise an exception" do
expect { ab_finished(:not_started_experiment) }.not_to raise_exception
end
it "should not change the user state when reset is false" do
expect { ab_finished(:not_started_experiment, reset: false) }.not_to change { ab_user.keys }.from([])
end
it "should not change the user state when reset is true" do
expect(self).not_to receive(:reset!)
ab_finished(:not_started_experiment)
end
it "should not increment the completed counter" do
ab_finished(:not_started_experiment)
expect(Split::Alternative.new("control", :not_started_experiment).completed_count).to eq(0)
expect(Split::Alternative.new("alt", :not_started_experiment).completed_count).to eq(0)
end
end
end
context "finished with config" do
it "passes reset option" do
Split.configuration.experiments = {
my_experiment: {
alternatives: ["one", "two"],
resettable: false,
}
}
alternative = ab_test(:my_experiment)
experiment = Split::ExperimentCatalog.find :my_experiment
ab_finished :my_experiment
expect(ab_user[experiment.key]).to eq(alternative)
expect(ab_user[experiment.finished_key]).to eq(true)
end
end
context "finished with metric name" do
before { Split.configuration.experiments = {} }
before { expect(Split::Alternative).to receive(:new).at_least(1).times.and_call_original }
def should_finish_experiment(experiment_name, should_finish = true)
alts = Split.configuration.experiments[experiment_name][:alternatives]
experiment = Split::ExperimentCatalog.find_or_create(experiment_name, *alts)
alt_name = ab_user[experiment.key] = alts.first
alt = double("alternative")
expect(alt).to receive(:name).at_most(1).times.and_return(alt_name)
expect(Split::Alternative).to receive(:new).at_most(1).times.with(alt_name, experiment_name.to_s).and_return(alt)
if should_finish
expect(alt).to receive(:increment_completion).at_most(1).times
else
expect(alt).not_to receive(:increment_completion)
end
end
it "completes the test" do
Split.configuration.experiments[:my_experiment] = {
alternatives: [ "control_opt", "other_opt" ],
metric: :my_metric
}
should_finish_experiment :my_experiment
ab_finished :my_metric
end
it "completes all relevant tests" do
Split.configuration.experiments = {
exp_1: {
alternatives: [ "1-1", "1-2" ],
metric: :my_metric
},
exp_2: {
alternatives: [ "2-1", "2-2" ],
metric: :another_metric
},
exp_3: {
alternatives: [ "3-1", "3-2" ],
metric: :my_metric
},
}
should_finish_experiment :exp_1
should_finish_experiment :exp_2, false
should_finish_experiment :exp_3
ab_finished :my_metric
end
it "passes reset option" do
Split.configuration.experiments = {
my_exp: {
alternatives: ["one", "two"],
metric: :my_metric,
resettable: false,
}
}
alternative_name = ab_test(:my_exp)
exp = Split::ExperimentCatalog.find :my_exp
ab_finished :my_metric
expect(ab_user[exp.key]).to eq(alternative_name)
expect(ab_user[exp.finished_key]).to be_truthy
end
it "passes through options" do
Split.configuration.experiments = {
my_exp: {
alternatives: ["one", "two"],
metric: :my_metric,
}
}
alternative_name = ab_test(:my_exp)
exp = Split::ExperimentCatalog.find :my_exp
ab_finished :my_metric, reset: false
expect(ab_user[exp.key]).to eq(alternative_name)
expect(ab_user[exp.finished_key]).to be_truthy
end
end
describe "conversions" do
it "should return a conversion rate for an alternative" do
alternative_name = ab_test("link_color", "blue", "red")
previous_convertion_rate = Split::Alternative.new(alternative_name, "link_color").conversion_rate
expect(previous_convertion_rate).to eq(0.0)
ab_finished("link_color")
new_convertion_rate = Split::Alternative.new(alternative_name, "link_color").conversion_rate
expect(new_convertion_rate).to eq(1.0)
end
end
describe "active experiments" do
it "should show an active test" do
alternative = ab_test("def", "4", "5", "6")
expect(active_experiments.count).to eq 1
expect(active_experiments.first[0]).to eq "def"
expect(active_experiments.first[1]).to eq alternative
end
it "should show a finished test" do
alternative = ab_test("def", "4", "5", "6")
ab_finished("def", { reset: false })
expect(active_experiments.count).to eq 1
expect(active_experiments.first[0]).to eq "def"
expect(active_experiments.first[1]).to eq alternative
end
it "should show an active test when an experiment is on a later version" do
experiment.reset
expect(experiment.version).to eq(1)
ab_test("link_color", "blue", "red")
expect(active_experiments.count).to eq 1
expect(active_experiments.first[0]).to eq "link_color"
end
it "should show versioned tests properly" do
10.times { experiment.reset }
alternative = ab_test(experiment.name, "blue", "red")
ab_finished(experiment.name, reset: false)
expect(experiment.version).to eq(10)
expect(active_experiments.count).to eq 1
expect(active_experiments).to eq({ "link_color" => alternative })
end
it "should show multiple tests" do
Split.configure do |config|
config.allow_multiple_experiments = true
end
alternative = ab_test("def", "4", "5", "6")
another_alternative = ab_test("ghi", "7", "8", "9")
expect(active_experiments.count).to eq 2
expect(active_experiments["def"]).to eq alternative
expect(active_experiments["ghi"]).to eq another_alternative
end
it "should not show tests with winners" do
Split.configure do |config|
config.allow_multiple_experiments = true
end
e = Split::ExperimentCatalog.find_or_create("def", "4", "5", "6")
e.winner = "4"
ab_test("def", "4", "5", "6")
another_alternative = ab_test("ghi", "7", "8", "9")
expect(active_experiments.count).to eq 1
expect(active_experiments.first[0]).to eq "ghi"
expect(active_experiments.first[1]).to eq another_alternative
end
end
describe "when user is a robot" do
before(:each) do
@request = OpenStruct.new(user_agent: "Googlebot/2.1 (+http://www.google.com/bot.html)")
end
describe "ab_test" do
it "should return the control" do
alternative = ab_test("link_color", "blue", "red")
expect(alternative).to eq experiment.control.name
end
it "should not create a experiment" do
ab_test("link_color", "blue", "red")
expect(Split::Experiment.new("link_color")).to be_a_new_record
end
it "should not increment the participation count" do
previous_red_count = Split::Alternative.new("red", "link_color").participant_count
previous_blue_count = Split::Alternative.new("blue", "link_color").participant_count
ab_test("link_color", "blue", "red")
new_red_count = Split::Alternative.new("red", "link_color").participant_count
new_blue_count = Split::Alternative.new("blue", "link_color").participant_count
expect((new_red_count + new_blue_count)).to eq(previous_red_count + previous_blue_count)
end
end
describe "finished" do
it "should not increment the completed count" do
alternative_name = ab_test("link_color", "blue", "red")
previous_completion_count = Split::Alternative.new(alternative_name, "link_color").completed_count
ab_finished("link_color")
new_completion_count = Split::Alternative.new(alternative_name, "link_color").completed_count
expect(new_completion_count).to eq(previous_completion_count)
end
end
end
describe "when providing custom ignore logic" do
context "using a proc to configure custom logic" do
before(:each) do
Split.configure do |c|
c.ignore_filter = proc { |request| true } # ignore everything
end
end
it "ignores the ab_test" do
ab_test("link_color", "blue", "red")
red_count = Split::Alternative.new("red", "link_color").participant_count
blue_count = Split::Alternative.new("blue", "link_color").participant_count
expect((red_count + blue_count)).to be(0)
end
end
end
shared_examples_for "a disabled test" do
describe "ab_test" do
it "should return the control" do
alternative = ab_test("link_color", "blue", "red")
expect(alternative).to eq experiment.control.name
end
it "should not increment the participation count" do
previous_red_count = Split::Alternative.new("red", "link_color").participant_count
previous_blue_count = Split::Alternative.new("blue", "link_color").participant_count
ab_test("link_color", "blue", "red")
new_red_count = Split::Alternative.new("red", "link_color").participant_count
new_blue_count = Split::Alternative.new("blue", "link_color").participant_count
expect((new_red_count + new_blue_count)).to eq(previous_red_count + previous_blue_count)
end
end
describe "finished" do
it "should not increment the completed count" do
alternative_name = ab_test("link_color", "blue", "red")
previous_completion_count = Split::Alternative.new(alternative_name, "link_color").completed_count
ab_finished("link_color")
new_completion_count = Split::Alternative.new(alternative_name, "link_color").completed_count
expect(new_completion_count).to eq(previous_completion_count)
end
end
end
describe "when ip address is ignored" do
context "individually" do
before(:each) do
@request = OpenStruct.new(ip: "81.19.48.130")
Split.configure do |c|
c.ignore_ip_addresses << "81.19.48.130"
end
end
it_behaves_like "a disabled test"
end
context "for a range" do
before(:each) do
@request = OpenStruct.new(ip: "81.19.48.129")
Split.configure do |c|
c.ignore_ip_addresses << /81\.19\.48\.[0-9]+/
end
end
it_behaves_like "a disabled test"
end
context "using both a range and a specific value" do
before(:each) do
@request = OpenStruct.new(ip: "81.19.48.128")
Split.configure do |c|
c.ignore_ip_addresses << "81.19.48.130"
c.ignore_ip_addresses << /81\.19\.48\.[0-9]+/
end
end
it_behaves_like "a disabled test"
end
context "when ignored other address" do
before do
@request = OpenStruct.new(ip: "1.1.1.1")
Split.configure do |c|
c.ignore_ip_addresses << "81.19.48.130"
end
end
it "works as usual" do
alternative_name = ab_test("link_color", "red", "blue")
expect {
ab_finished("link_color")
}.to change(Split::Alternative.new(alternative_name, "link_color"), :completed_count).by(1)
end
end
end
describe "when user is previewing" do
before(:each) do
@request = OpenStruct.new(headers: { "x-purpose" => "preview" })
end
it_behaves_like "a disabled test"
end
describe "versioned experiments" do
it "should use version zero if no version is present" do
alternative_name = ab_test("link_color", "blue", "red")
expect(experiment.version).to eq(0)
expect(ab_user["link_color"]).to eq(alternative_name)
end
it "should save the version of the experiment to the session" do
experiment.reset
expect(experiment.version).to eq(1)
alternative_name = ab_test("link_color", "blue", "red")
expect(ab_user["link_color:1"]).to eq(alternative_name)
end
it "should load the experiment even if the version is not 0" do
experiment.reset
expect(experiment.version).to eq(1)
alternative_name = ab_test("link_color", "blue", "red")
expect(ab_user["link_color:1"]).to eq(alternative_name)
return_alternative_name = ab_test("link_color", "blue", "red")
expect(return_alternative_name).to eq(alternative_name)
end
it "should reset the session of a user on an older version of the experiment" do
alternative_name = ab_test("link_color", "blue", "red")
expect(ab_user["link_color"]).to eq(alternative_name)
alternative = Split::Alternative.new(alternative_name, "link_color")
expect(alternative.participant_count).to eq(1)
experiment.reset
expect(experiment.version).to eq(1)
alternative = Split::Alternative.new(alternative_name, "link_color")
expect(alternative.participant_count).to eq(0)
new_alternative_name = ab_test("link_color", "blue", "red")
expect(ab_user["link_color:1"]).to eq(new_alternative_name)
new_alternative = Split::Alternative.new(new_alternative_name, "link_color")
expect(new_alternative.participant_count).to eq(1)
end
it "should cleanup old versions of experiments from the session" do
alternative_name = ab_test("link_color", "blue", "red")
expect(ab_user["link_color"]).to eq(alternative_name)
alternative = Split::Alternative.new(alternative_name, "link_color")
expect(alternative.participant_count).to eq(1)
experiment.reset
expect(experiment.version).to eq(1)
alternative = Split::Alternative.new(alternative_name, "link_color")
expect(alternative.participant_count).to eq(0)
new_alternative_name = ab_test("link_color", "blue", "red")
expect(ab_user["link_color:1"]).to eq(new_alternative_name)
end
it "should only count completion of users on the current version" do
alternative_name = ab_test("link_color", "blue", "red")
expect(ab_user["link_color"]).to eq(alternative_name)
Split::Alternative.new(alternative_name, "link_color")
experiment.reset
expect(experiment.version).to eq(1)
ab_finished("link_color")
alternative = Split::Alternative.new(alternative_name, "link_color")
expect(alternative.completed_count).to eq(0)
end
end
context "when redis is not available" do
before(:each) do
expect(Split).to receive(:redis).at_most(5).times.and_raise(Errno::ECONNREFUSED.new)
end
context "and db_failover config option is turned off" do
before(:each) do
Split.configure do |config|
config.db_failover = false
end
end
describe "ab_test" do
it "should raise an exception" do
expect { ab_test("link_color", "blue", "red") }.to raise_error(Errno::ECONNREFUSED)
end
end
describe "finished" do
it "should raise an exception" do
expect { ab_finished("link_color") }.to raise_error(Errno::ECONNREFUSED)
end
end
describe "disable split testing" do
before(:each) do
Split.configure do |config|
config.enabled = false
end
end
it "should not attempt to connect to redis" do
expect { ab_test("link_color", "blue", "red") }.not_to raise_error
end
it "should return control variable" do
expect(ab_test("link_color", "blue", "red")).to eq("blue")
expect { ab_finished("link_color") }.not_to raise_error
end
end
end
context "and db_failover config option is turned on" do
before(:each) do
Split.configure do |config|
config.db_failover = true
end
end
describe "ab_test" do
it "should not raise an exception" do
expect { ab_test("link_color", "blue", "red") }.not_to raise_error
end
it "should call db_failover_on_db_error proc with error as parameter" do
Split.configure do |config|
config.db_failover_on_db_error = proc do |error|
expect(error).to be_a(Errno::ECONNREFUSED)
end
end
expect(Split.configuration.db_failover_on_db_error).to receive(:call).and_call_original
ab_test("link_color", "blue", "red")
end
it "should always use first alternative" do
expect(ab_test("link_color", "blue", "red")).to eq("blue")
expect(ab_test("link_color", { "blue" => 0.01 }, "red" => 0.2)).to eq("blue")
expect(ab_test("link_color", { "blue" => 0.8 }, { "red" => 20 })).to eq("blue")
expect(ab_test("link_color", "blue", "red") do |alternative|
"shared/#{alternative}"
end).to eq("shared/blue")
end
context "and db_failover_allow_parameter_override config option is turned on" do
before(:each) do
Split.configure do |config|
config.db_failover_allow_parameter_override = true
end
end
context "and given an override parameter" do
it "should use given override instead of the first alternative" do
@params = { "ab_test" => { "link_color" => "red" } }
expect(ab_test("link_color", "blue", "red")).to eq("red")
expect(ab_test("link_color", "blue", "red", "green")).to eq("red")
expect(ab_test("link_color", { "blue" => 0.01 }, "red" => 0.2)).to eq("red")
expect(ab_test("link_color", { "blue" => 0.8 }, { "red" => 20 })).to eq("red")
expect(ab_test("link_color", "blue", "red") do |alternative|
"shared/#{alternative}"
end).to eq("shared/red")
end
end
end
context "and preloaded config given" do
before do
Split.configuration.experiments[:link_color] = {
alternatives: [ "blue", "red" ],
}
end
it "uses first alternative" do
expect(ab_test(:link_color)).to eq("blue")
end
end
end
describe "finished" do
it "should not raise an exception" do
expect { ab_finished("link_color") }.not_to raise_error
end
it "should call db_failover_on_db_error proc with error as parameter" do
Split.configure do |config|
config.db_failover_on_db_error = proc do |error|
expect(error).to be_a(Errno::ECONNREFUSED)
end
end
expect(Split.configuration.db_failover_on_db_error).to receive(:call).and_call_original
ab_finished("link_color")
end
end
end
end
context "with preloaded config" do
before { Split.configuration.experiments = {} }
it "pulls options from config file" do
Split.configuration.experiments[:my_experiment] = {
alternatives: [ "control_opt", "other_opt" ],
goals: ["goal1", "goal2"]
}
ab_test :my_experiment
expect(Split::Experiment.new(:my_experiment).alternatives.map(&:name)).to eq([ "control_opt", "other_opt" ])
expect(Split::Experiment.new(:my_experiment).goals).to eq([ "goal1", "goal2" ])
end
it "can be called multiple times" do
Split.configuration.experiments[:my_experiment] = {
alternatives: [ "control_opt", "other_opt" ],
goals: ["goal1", "goal2"]
}
5.times { ab_test :my_experiment }
experiment = Split::Experiment.new(:my_experiment)
expect(experiment.alternatives.map(&:name)).to eq([ "control_opt", "other_opt" ])
expect(experiment.goals).to eq([ "goal1", "goal2" ])
expect(experiment.participant_count).to eq(1)
end
it "accepts multiple goals" do
Split.configuration.experiments[:my_experiment] = {
alternatives: [ "control_opt", "other_opt" ],
goals: [ "goal1", "goal2", "goal3" ]
}
ab_test :my_experiment
experiment = Split::Experiment.new(:my_experiment)
expect(experiment.goals).to eq([ "goal1", "goal2", "goal3" ])
end
it "allow specifying goals to be optional" do
Split.configuration.experiments[:my_experiment] = {
alternatives: [ "control_opt", "other_opt" ]
}
experiment = Split::Experiment.new(:my_experiment)
expect(experiment.goals).to eq([])
end
it "accepts multiple alternatives" do
Split.configuration.experiments[:my_experiment] = {
alternatives: [ "control_opt", "second_opt", "third_opt" ],
}
ab_test :my_experiment
experiment = Split::Experiment.new(:my_experiment)
expect(experiment.alternatives.map(&:name)).to eq([ "control_opt", "second_opt", "third_opt" ])
end
it "accepts probability on alternatives" do
Split.configuration.experiments[:my_experiment] = {
alternatives: [
{ name: "control_opt", percent: 67 },
{ name: "second_opt", percent: 10 },
{ name: "third_opt", percent: 23 },
],
}
ab_test :my_experiment
experiment = Split::Experiment.new(:my_experiment)
expect(experiment.alternatives.collect { |a| [a.name, a.weight] }).to eq([["control_opt", 0.67], ["second_opt", 0.1], ["third_opt", 0.23]])
end
it "accepts probability on some alternatives" do
Split.configuration.experiments[:my_experiment] = {
alternatives: [
{ name: "control_opt", percent: 34 },
"second_opt",
{ name: "third_opt", percent: 23 },
"fourth_opt",
],
}
ab_test :my_experiment
experiment = Split::Experiment.new(:my_experiment)
names_and_weights = experiment.alternatives.collect { |a| [a.name, a.weight] }
expect(names_and_weights).to eq([["control_opt", 0.34], ["second_opt", 0.215], ["third_opt", 0.23], ["fourth_opt", 0.215]])
expect(names_and_weights.inject(0) { |sum, nw| sum + nw[1] }).to eq(1.0)
end
it "allows name param without probability" do
Split.configuration.experiments[:my_experiment] = {
alternatives: [
{ name: "control_opt" },
"second_opt",
{ name: "third_opt", percent: 64 },
],
}
ab_test :my_experiment
experiment = Split::Experiment.new(:my_experiment)
names_and_weights = experiment.alternatives.collect { |a| [a.name, a.weight] }
expect(names_and_weights).to eq([["control_opt", 0.18], ["second_opt", 0.18], ["third_opt", 0.64]])
expect(names_and_weights.inject(0) { |sum, nw| sum + nw[1] }).to eq(1.0)
end
it "fails gracefully if config is missing experiment" do
Split.configuration.experiments = { other_experiment: { foo: "Bar" } }
expect { ab_test :my_experiment }.to raise_error(Split::ExperimentNotFound)
end
it "fails gracefully if config is missing" do
expect { Split.configuration.experiments = nil }.to raise_error(Split::InvalidExperimentsFormatError)
end
it "fails gracefully if config is missing alternatives" do
Split.configuration.experiments[:my_experiment] = { foo: "Bar" }
expect { ab_test :my_experiment }.to raise_error(NoMethodError)
end
end
it "should handle multiple experiments correctly" do
experiment2 = Split::ExperimentCatalog.find_or_create("link_color2", "blue", "red")
ab_test("link_color", "blue", "red")
ab_test("link_color2", "blue", "red")
ab_finished("link_color2")
experiment2.alternatives.each do |alt|
expect(alt.unfinished_count).to eq(0)
end
end
context "with goals" do
before do
@experiment = { "link_color" => ["purchase", "refund"] }
@alternatives = ["blue", "red"]
@experiment_name, @goals = normalize_metric(@experiment)
@goal1 = @goals[0]
@goal2 = @goals[1]
end
it "should normalize experiment" do
expect(@experiment_name).to eq("link_color")
expect(@goals).to eq(["purchase", "refund"])
end
describe "ab_test" do
it "should allow experiment goals interface as a single hash" do
ab_test(@experiment, *@alternatives)
experiment = Split::ExperimentCatalog.find("link_color")
expect(experiment.goals).to eq(["purchase", "refund"])
end
end
describe "ab_finished" do
before do
@alternative_name = ab_test(@experiment, *@alternatives)
end
it "should increment the counter for the specified-goal completed alternative" do
expect { ab_finished({ "link_color" => ["purchase"] }) }
.to change { Split::Alternative.new(@alternative_name, @experiment_name).completed_count(@goal2) }.by(0)
.and change { Split::Alternative.new(@alternative_name, @experiment_name).completed_count(@goal1) }.by(1)
end
end
end
end
<MSG> Merge pull request #263 from hwartig/option-to-disable-split
Provide an option to generically disable Split.
<DFF> @@ -113,6 +113,24 @@ describe Split::Helper do
ab_test('link_color', 'blue', 'red')
end
+ it "SPLIT_DISABLE query parameter should also force the alternative (uses control)" do
+ @params = {'SPLIT_DISABLE' => 'true'}
+ alternative = ab_test('link_color', 'blue', 'red')
+ alternative.should eql('blue')
+ alternative = ab_test('link_color', {'blue' => 1}, 'red' => 5)
+ alternative.should eql('blue')
+ alternative = ab_test('link_color', 'red', 'blue')
+ alternative.should eql('red')
+ alternative = ab_test('link_color', {'red' => 5}, 'blue' => 1)
+ alternative.should eql('red')
+ end
+
+ it "should not store the split when Split generically disabled" do
+ @params = {'SPLIT_DISABLE' => 'true'}
+ ab_user.should_not_receive(:[]=)
+ ab_test('link_color', 'blue', 'red')
+ end
+
context "when store_override is set" do
before { Split.configuration.store_override = true }
| 18 | Merge pull request #263 from hwartig/option-to-disable-split | 0 | .rb | rb | mit | splitrb/split |
10071947 | <NME> helper_spec.rb
<BEF> # frozen_string_literal: true
require "spec_helper"
# TODO change some of these tests to use Rack::Test
describe Split::Helper do
include Split::Helper
let(:experiment) {
Split::ExperimentCatalog.find_or_create("link_color", "blue", "red")
}
describe "ab_test" do
it "should not raise an error when passed strings for alternatives" do
expect { ab_test("xyz", "1", "2", "3") }.not_to raise_error
end
it "should not raise an error when passed an array for alternatives" do
expect { ab_test("xyz", ["1", "2", "3"]) }.not_to raise_error
end
it "should raise the appropriate error when passed integers for alternatives" do
expect { ab_test("xyz", 1, 2, 3) }.to raise_error(ArgumentError)
end
it "should raise the appropriate error when passed symbols for alternatives" do
expect { ab_test("xyz", :a, :b, :c) }.to raise_error(ArgumentError)
end
it "should not raise error when passed an array for goals" do
expect { ab_test({ "link_color" => ["purchase", "refund"] }, "blue", "red") }.not_to raise_error
end
it "should not raise error when passed just one goal" do
expect { ab_test({ "link_color" => "purchase" }, "blue", "red") }.not_to raise_error
end
it "raises an appropriate error when processing combined expirements" do
Split.configuration.experiments = {
combined_exp_1: {
alternatives: [ { name: "control", percent: 50 }, { name: "test-alt", percent: 50 } ],
metric: :my_metric,
combined_experiments: [:combined_exp_1_sub_1]
}
}
Split::ExperimentCatalog.find_or_create("combined_exp_1")
expect { ab_test("combined_exp_1") }.to raise_error(Split::InvalidExperimentsFormatError)
end
it "should assign a random alternative to a new user when there are an equal number of alternatives assigned" do
ab_test("link_color", "blue", "red")
expect(["red", "blue"]).to include(ab_user["link_color"])
end
it "should increment the participation counter after assignment to a new user" do
previous_red_count = Split::Alternative.new("red", "link_color").participant_count
previous_blue_count = Split::Alternative.new("blue", "link_color").participant_count
ab_test("link_color", "blue", "red")
new_red_count = Split::Alternative.new("red", "link_color").participant_count
new_blue_count = Split::Alternative.new("blue", "link_color").participant_count
expect((new_red_count + new_blue_count)).to eq(previous_red_count + previous_blue_count + 1)
end
it "should not increment the counter for an experiment that the user is not participating in" do
ab_test("link_color", "blue", "red")
e = Split::ExperimentCatalog.find_or_create("button_size", "small", "big")
expect {
# User shouldn't participate in this second experiment
ab_test("button_size", "small", "big")
}.not_to change { e.participant_count }
end
it "should not increment the counter for an ended experiment" do
e = Split::ExperimentCatalog.find_or_create("button_size", "small", "big")
e.winner = "small"
expect {
a = ab_test("button_size", "small", "big")
expect(a).to eq("small")
}.not_to change { e.participant_count }
end
it "should not increment the counter for an not started experiment" do
expect(Split.configuration).to receive(:start_manually).and_return(true)
e = Split::ExperimentCatalog.find_or_create("button_size", "small", "big")
expect {
a = ab_test("button_size", "small", "big")
expect(a).to eq("small")
}.not_to change { e.participant_count }
end
it "should return the given alternative for an existing user" do
expect(ab_test("link_color", "blue", "red")).to eq ab_test("link_color", "blue", "red")
end
it "should always return the winner if one is present" do
experiment.winner = "orange"
expect(ab_test("link_color", "blue", "red")).to eq("orange")
end
it "should allow the alternative to be forced by passing it in the params" do
# ?ab_test[link_color]=blue
@params = { "ab_test" => { "link_color" => "blue" } }
alternative = ab_test("link_color", "blue", "red")
expect(alternative).to eq("blue")
alternative = ab_test("link_color", { "blue" => 1 }, "red" => 5)
ab_test('link_color', 'blue', 'red')
end
context "when store_override is set" do
before { Split.configuration.store_override = true }
@params = { "SPLIT_DISABLE" => "true" }
alternative = ab_test("link_color", "blue", "red")
expect(alternative).to eq("blue")
alternative = ab_test("link_color", { "blue" => 1 }, "red" => 5)
expect(alternative).to eq("blue")
alternative = ab_test("link_color", "red", "blue")
expect(alternative).to eq("red")
alternative = ab_test("link_color", { "red" => 5 }, "blue" => 1)
expect(alternative).to eq("red")
end
it "should not store the split when Split generically disabled" do
@params = { "SPLIT_DISABLE" => "true" }
expect(ab_user).not_to receive(:[]=)
ab_test("link_color", "blue", "red")
end
context "when store_override is set" do
before { Split.configuration.store_override = true }
it "should store the forced alternative" do
@params = { "ab_test" => { "link_color" => "blue" } }
expect(ab_user).to receive(:[]=).with("link_color", "blue")
ab_test("link_color", "blue", "red")
end
end
context "when on_trial_choose is set" do
before { Split.configuration.on_trial_choose = :some_method }
it "should call the method" do
expect(self).to receive(:some_method)
ab_test("link_color", "blue", "red")
end
end
it "should allow passing a block" do
alt = ab_test("link_color", "blue", "red")
ret = ab_test("link_color", "blue", "red") { |alternative| "shared/#{alternative}" }
expect(ret).to eq("shared/#{alt}")
end
it "should allow the share of visitors see an alternative to be specified" do
ab_test("link_color", { "blue" => 0.8 }, { "red" => 20 })
expect(["red", "blue"]).to include(ab_user["link_color"])
end
it "should allow alternative weighting interface as a single hash" do
ab_test("link_color", { "blue" => 0.01 }, "red" => 0.2)
experiment = Split::ExperimentCatalog.find("link_color")
expect(experiment.alternatives.map(&:name)).to eq(["blue", "red"])
expect(experiment.alternatives.collect { |a| a.weight }).to match_array([0.01, 0.2])
end
it "should only let a user participate in one experiment at a time" do
link_color = ab_test("link_color", "blue", "red")
ab_test("button_size", "small", "big")
expect(ab_user["link_color"]).to eq(link_color)
big = Split::Alternative.new("big", "button_size")
expect(big.participant_count).to eq(0)
small = Split::Alternative.new("small", "button_size")
expect(small.participant_count).to eq(0)
end
it "should let a user participate in many experiment with allow_multiple_experiments option" do
Split.configure do |config|
config.allow_multiple_experiments = true
end
link_color = ab_test("link_color", "blue", "red")
button_size = ab_test("button_size", "small", "big")
expect(ab_user["link_color"]).to eq(link_color)
expect(ab_user["button_size"]).to eq(button_size)
button_size_alt = Split::Alternative.new(button_size, "button_size")
expect(button_size_alt.participant_count).to eq(1)
end
context "with allow_multiple_experiments = 'control'" do
it "should let a user participate in many experiment with one non-'control' alternative" do
Split.configure do |config|
config.allow_multiple_experiments = "control"
end
groups = 100.times.map do |n|
ab_test("test#{n}".to_sym, { "control" => (100 - n) }, { "test#{n}-alt" => n })
end
experiments = ab_user.active_experiments
expect(experiments.size).to be > 1
count_control = experiments.values.count { |g| g == "control" }
expect(count_control).to eq(experiments.size - 1)
count_alts = groups.count { |g| g != "control" }
expect(count_alts).to eq(1)
end
context "when user already has experiment" do
let(:mock_user) { Split::User.new(self, { "test_0" => "test-alt" }) }
before do
Split.configure do |config|
config.allow_multiple_experiments = "control"
end
Split::ExperimentCatalog.find_or_initialize("test_0", "control", "test-alt").save
Split::ExperimentCatalog.find_or_initialize("test_1", "control", "test-alt").save
end
it "should restore previously selected alternative" do
expect(ab_user.active_experiments.size).to eq 1
expect(ab_test(:test_0, { "control" => 100 }, { "test-alt" => 1 })).to eq "test-alt"
expect(ab_test(:test_0, { "control" => 1 }, { "test-alt" => 100 })).to eq "test-alt"
end
it "should select the correct alternatives after experiment resets" do
experiment = Split::ExperimentCatalog.find(:test_0)
experiment.reset
mock_user[experiment.key] = "test-alt"
expect(ab_user.active_experiments.size).to eq 1
expect(ab_test(:test_0, { "control" => 100 }, { "test-alt" => 1 })).to eq "test-alt"
expect(ab_test(:test_0, { "control" => 0 }, { "test-alt" => 100 })).to eq "test-alt"
end
it "lets override existing choice" do
pending "this requires user store reset on first call not depending on whelther it is current trial"
@params = { "ab_test" => { "test_1" => "test-alt" } }
expect(ab_test(:test_0, { "control" => 0 }, { "test-alt" => 100 })).to eq "control"
expect(ab_test(:test_1, { "control" => 100 }, { "test-alt" => 1 })).to eq "test-alt"
end
end
end
it "should not over-write a finished key when an experiment is on a later version" do
experiment.increment_version
ab_user = { experiment.key => "blue", experiment.finished_key => true }
finished_session = ab_user.dup
ab_test("link_color", "blue", "red")
expect(ab_user).to eq(finished_session)
end
end
describe "metadata" do
context "is defined" do
before do
Split.configuration.experiments = {
my_experiment: {
alternatives: ["one", "two"],
resettable: false,
metadata: { "one" => "Meta1", "two" => "Meta2" }
}
}
end
it "should be passed to helper block" do
@params = { "ab_test" => { "my_experiment" => "two" } }
expect(ab_test("my_experiment")).to eq "two"
expect(ab_test("my_experiment") do |alternative, meta|
meta
end).to eq("Meta2")
end
it "should pass control metadata helper block if library disabled" do
Split.configure do |config|
config.enabled = false
end
expect(ab_test("my_experiment")).to eq "one"
expect(ab_test("my_experiment") do |_, meta|
meta
end).to eq("Meta1")
end
end
context "is not defined" do
before do
Split.configuration.experiments = {
my_experiment: {
alternatives: ["one", "two"],
resettable: false,
metadata: nil
}
}
end
it "should be passed to helper block" do
expect(ab_test("my_experiment") do |alternative, meta|
meta
end).to eq({})
end
it "should pass control metadata helper block if library disabled" do
Split.configure do |config|
config.enabled = false
end
expect(ab_test("my_experiment") do |_, meta|
meta
end).to eq({})
end
end
end
describe "ab_finished" do
context "for an experiment that the user participates in" do
before(:each) do
@experiment_name = "link_color"
@alternatives = ["blue", "red"]
@experiment = Split::ExperimentCatalog.find_or_create(@experiment_name, *@alternatives)
@alternative_name = ab_test(@experiment_name, *@alternatives)
@previous_completion_count = Split::Alternative.new(@alternative_name, @experiment_name).completed_count
end
it "should increment the counter for the completed alternative" do
ab_finished(@experiment_name)
new_completion_count = Split::Alternative.new(@alternative_name, @experiment_name).completed_count
expect(new_completion_count).to eq(@previous_completion_count + 1)
end
it "should set experiment's finished key if reset is false" do
ab_finished(@experiment_name, { reset: false })
expect(ab_user[@experiment.key]).to eq(@alternative_name)
expect(ab_user[@experiment.finished_key]).to eq(true)
end
it "should not increment the counter if reset is false and the experiment has been already finished" do
2.times { ab_finished(@experiment_name, { reset: false }) }
new_completion_count = Split::Alternative.new(@alternative_name, @experiment_name).completed_count
expect(new_completion_count).to eq(@previous_completion_count + 1)
end
it "should not increment the counter for an ended experiment" do
e = Split::ExperimentCatalog.find_or_create("button_size", "small", "big")
e.winner = "small"
a = ab_test("button_size", "small", "big")
expect(a).to eq("small")
expect {
ab_finished("button_size")
}.not_to change { Split::Alternative.new(a, "button_size").completed_count }
end
it "should clear out the user's participation from their session" do
expect(ab_user[@experiment.key]).to eq(@alternative_name)
ab_finished(@experiment_name)
expect(ab_user.keys).to be_empty
end
it "should not clear out the users session if reset is false" do
expect(ab_user[@experiment.key]).to eq(@alternative_name)
ab_finished(@experiment_name, { reset: false })
expect(ab_user[@experiment.key]).to eq(@alternative_name)
expect(ab_user[@experiment.finished_key]).to eq(true)
end
it "should reset the users session when experiment is not versioned" do
expect(ab_user[@experiment.key]).to eq(@alternative_name)
ab_finished(@experiment_name)
expect(ab_user.keys).to be_empty
end
it "should reset the users session when experiment is versioned" do
@experiment.increment_version
@alternative_name = ab_test(@experiment_name, *@alternatives)
expect(ab_user[@experiment.key]).to eq(@alternative_name)
ab_finished(@experiment_name)
expect(ab_user.keys).to be_empty
end
context "when on_trial_complete is set" do
before { Split.configuration.on_trial_complete = :some_method }
it "should call the method" do
expect(self).to receive(:some_method)
ab_finished(@experiment_name)
end
it "should not call the method without alternative" do
ab_user[@experiment.key] = nil
expect(self).not_to receive(:some_method)
ab_finished(@experiment_name)
end
end
end
context "for an experiment that the user is excluded from" do
before do
alternative = ab_test("link_color", "blue", "red")
expect(Split::Alternative.new(alternative, "link_color").participant_count).to eq(1)
alternative = ab_test("button_size", "small", "big")
expect(Split::Alternative.new(alternative, "button_size").participant_count).to eq(0)
end
it "should not increment the completed counter" do
# So, user should be participating in the link_color experiment and
# receive the control for button_size. As the user is not participating in
# the button size experiment, finishing it should not increase the
# completion count for that alternative.
expect {
ab_finished("button_size")
}.not_to change { Split::Alternative.new("small", "button_size").completed_count }
end
end
context "for an experiment that the user does not participate in" do
before do
Split::ExperimentCatalog.find_or_create(:not_started_experiment, "control", "alt")
end
it "should not raise an exception" do
expect { ab_finished(:not_started_experiment) }.not_to raise_exception
end
it "should not change the user state when reset is false" do
expect { ab_finished(:not_started_experiment, reset: false) }.not_to change { ab_user.keys }.from([])
end
it "should not change the user state when reset is true" do
expect(self).not_to receive(:reset!)
ab_finished(:not_started_experiment)
end
it "should not increment the completed counter" do
ab_finished(:not_started_experiment)
expect(Split::Alternative.new("control", :not_started_experiment).completed_count).to eq(0)
expect(Split::Alternative.new("alt", :not_started_experiment).completed_count).to eq(0)
end
end
end
context "finished with config" do
it "passes reset option" do
Split.configuration.experiments = {
my_experiment: {
alternatives: ["one", "two"],
resettable: false,
}
}
alternative = ab_test(:my_experiment)
experiment = Split::ExperimentCatalog.find :my_experiment
ab_finished :my_experiment
expect(ab_user[experiment.key]).to eq(alternative)
expect(ab_user[experiment.finished_key]).to eq(true)
end
end
context "finished with metric name" do
before { Split.configuration.experiments = {} }
before { expect(Split::Alternative).to receive(:new).at_least(1).times.and_call_original }
def should_finish_experiment(experiment_name, should_finish = true)
alts = Split.configuration.experiments[experiment_name][:alternatives]
experiment = Split::ExperimentCatalog.find_or_create(experiment_name, *alts)
alt_name = ab_user[experiment.key] = alts.first
alt = double("alternative")
expect(alt).to receive(:name).at_most(1).times.and_return(alt_name)
expect(Split::Alternative).to receive(:new).at_most(1).times.with(alt_name, experiment_name.to_s).and_return(alt)
if should_finish
expect(alt).to receive(:increment_completion).at_most(1).times
else
expect(alt).not_to receive(:increment_completion)
end
end
it "completes the test" do
Split.configuration.experiments[:my_experiment] = {
alternatives: [ "control_opt", "other_opt" ],
metric: :my_metric
}
should_finish_experiment :my_experiment
ab_finished :my_metric
end
it "completes all relevant tests" do
Split.configuration.experiments = {
exp_1: {
alternatives: [ "1-1", "1-2" ],
metric: :my_metric
},
exp_2: {
alternatives: [ "2-1", "2-2" ],
metric: :another_metric
},
exp_3: {
alternatives: [ "3-1", "3-2" ],
metric: :my_metric
},
}
should_finish_experiment :exp_1
should_finish_experiment :exp_2, false
should_finish_experiment :exp_3
ab_finished :my_metric
end
it "passes reset option" do
Split.configuration.experiments = {
my_exp: {
alternatives: ["one", "two"],
metric: :my_metric,
resettable: false,
}
}
alternative_name = ab_test(:my_exp)
exp = Split::ExperimentCatalog.find :my_exp
ab_finished :my_metric
expect(ab_user[exp.key]).to eq(alternative_name)
expect(ab_user[exp.finished_key]).to be_truthy
end
it "passes through options" do
Split.configuration.experiments = {
my_exp: {
alternatives: ["one", "two"],
metric: :my_metric,
}
}
alternative_name = ab_test(:my_exp)
exp = Split::ExperimentCatalog.find :my_exp
ab_finished :my_metric, reset: false
expect(ab_user[exp.key]).to eq(alternative_name)
expect(ab_user[exp.finished_key]).to be_truthy
end
end
describe "conversions" do
it "should return a conversion rate for an alternative" do
alternative_name = ab_test("link_color", "blue", "red")
previous_convertion_rate = Split::Alternative.new(alternative_name, "link_color").conversion_rate
expect(previous_convertion_rate).to eq(0.0)
ab_finished("link_color")
new_convertion_rate = Split::Alternative.new(alternative_name, "link_color").conversion_rate
expect(new_convertion_rate).to eq(1.0)
end
end
describe "active experiments" do
it "should show an active test" do
alternative = ab_test("def", "4", "5", "6")
expect(active_experiments.count).to eq 1
expect(active_experiments.first[0]).to eq "def"
expect(active_experiments.first[1]).to eq alternative
end
it "should show a finished test" do
alternative = ab_test("def", "4", "5", "6")
ab_finished("def", { reset: false })
expect(active_experiments.count).to eq 1
expect(active_experiments.first[0]).to eq "def"
expect(active_experiments.first[1]).to eq alternative
end
it "should show an active test when an experiment is on a later version" do
experiment.reset
expect(experiment.version).to eq(1)
ab_test("link_color", "blue", "red")
expect(active_experiments.count).to eq 1
expect(active_experiments.first[0]).to eq "link_color"
end
it "should show versioned tests properly" do
10.times { experiment.reset }
alternative = ab_test(experiment.name, "blue", "red")
ab_finished(experiment.name, reset: false)
expect(experiment.version).to eq(10)
expect(active_experiments.count).to eq 1
expect(active_experiments).to eq({ "link_color" => alternative })
end
it "should show multiple tests" do
Split.configure do |config|
config.allow_multiple_experiments = true
end
alternative = ab_test("def", "4", "5", "6")
another_alternative = ab_test("ghi", "7", "8", "9")
expect(active_experiments.count).to eq 2
expect(active_experiments["def"]).to eq alternative
expect(active_experiments["ghi"]).to eq another_alternative
end
it "should not show tests with winners" do
Split.configure do |config|
config.allow_multiple_experiments = true
end
e = Split::ExperimentCatalog.find_or_create("def", "4", "5", "6")
e.winner = "4"
ab_test("def", "4", "5", "6")
another_alternative = ab_test("ghi", "7", "8", "9")
expect(active_experiments.count).to eq 1
expect(active_experiments.first[0]).to eq "ghi"
expect(active_experiments.first[1]).to eq another_alternative
end
end
describe "when user is a robot" do
before(:each) do
@request = OpenStruct.new(user_agent: "Googlebot/2.1 (+http://www.google.com/bot.html)")
end
describe "ab_test" do
it "should return the control" do
alternative = ab_test("link_color", "blue", "red")
expect(alternative).to eq experiment.control.name
end
it "should not create a experiment" do
ab_test("link_color", "blue", "red")
expect(Split::Experiment.new("link_color")).to be_a_new_record
end
it "should not increment the participation count" do
previous_red_count = Split::Alternative.new("red", "link_color").participant_count
previous_blue_count = Split::Alternative.new("blue", "link_color").participant_count
ab_test("link_color", "blue", "red")
new_red_count = Split::Alternative.new("red", "link_color").participant_count
new_blue_count = Split::Alternative.new("blue", "link_color").participant_count
expect((new_red_count + new_blue_count)).to eq(previous_red_count + previous_blue_count)
end
end
describe "finished" do
it "should not increment the completed count" do
alternative_name = ab_test("link_color", "blue", "red")
previous_completion_count = Split::Alternative.new(alternative_name, "link_color").completed_count
ab_finished("link_color")
new_completion_count = Split::Alternative.new(alternative_name, "link_color").completed_count
expect(new_completion_count).to eq(previous_completion_count)
end
end
end
describe "when providing custom ignore logic" do
context "using a proc to configure custom logic" do
before(:each) do
Split.configure do |c|
c.ignore_filter = proc { |request| true } # ignore everything
end
end
it "ignores the ab_test" do
ab_test("link_color", "blue", "red")
red_count = Split::Alternative.new("red", "link_color").participant_count
blue_count = Split::Alternative.new("blue", "link_color").participant_count
expect((red_count + blue_count)).to be(0)
end
end
end
shared_examples_for "a disabled test" do
describe "ab_test" do
it "should return the control" do
alternative = ab_test("link_color", "blue", "red")
expect(alternative).to eq experiment.control.name
end
it "should not increment the participation count" do
previous_red_count = Split::Alternative.new("red", "link_color").participant_count
previous_blue_count = Split::Alternative.new("blue", "link_color").participant_count
ab_test("link_color", "blue", "red")
new_red_count = Split::Alternative.new("red", "link_color").participant_count
new_blue_count = Split::Alternative.new("blue", "link_color").participant_count
expect((new_red_count + new_blue_count)).to eq(previous_red_count + previous_blue_count)
end
end
describe "finished" do
it "should not increment the completed count" do
alternative_name = ab_test("link_color", "blue", "red")
previous_completion_count = Split::Alternative.new(alternative_name, "link_color").completed_count
ab_finished("link_color")
new_completion_count = Split::Alternative.new(alternative_name, "link_color").completed_count
expect(new_completion_count).to eq(previous_completion_count)
end
end
end
describe "when ip address is ignored" do
context "individually" do
before(:each) do
@request = OpenStruct.new(ip: "81.19.48.130")
Split.configure do |c|
c.ignore_ip_addresses << "81.19.48.130"
end
end
it_behaves_like "a disabled test"
end
context "for a range" do
before(:each) do
@request = OpenStruct.new(ip: "81.19.48.129")
Split.configure do |c|
c.ignore_ip_addresses << /81\.19\.48\.[0-9]+/
end
end
it_behaves_like "a disabled test"
end
context "using both a range and a specific value" do
before(:each) do
@request = OpenStruct.new(ip: "81.19.48.128")
Split.configure do |c|
c.ignore_ip_addresses << "81.19.48.130"
c.ignore_ip_addresses << /81\.19\.48\.[0-9]+/
end
end
it_behaves_like "a disabled test"
end
context "when ignored other address" do
before do
@request = OpenStruct.new(ip: "1.1.1.1")
Split.configure do |c|
c.ignore_ip_addresses << "81.19.48.130"
end
end
it "works as usual" do
alternative_name = ab_test("link_color", "red", "blue")
expect {
ab_finished("link_color")
}.to change(Split::Alternative.new(alternative_name, "link_color"), :completed_count).by(1)
end
end
end
describe "when user is previewing" do
before(:each) do
@request = OpenStruct.new(headers: { "x-purpose" => "preview" })
end
it_behaves_like "a disabled test"
end
describe "versioned experiments" do
it "should use version zero if no version is present" do
alternative_name = ab_test("link_color", "blue", "red")
expect(experiment.version).to eq(0)
expect(ab_user["link_color"]).to eq(alternative_name)
end
it "should save the version of the experiment to the session" do
experiment.reset
expect(experiment.version).to eq(1)
alternative_name = ab_test("link_color", "blue", "red")
expect(ab_user["link_color:1"]).to eq(alternative_name)
end
it "should load the experiment even if the version is not 0" do
experiment.reset
expect(experiment.version).to eq(1)
alternative_name = ab_test("link_color", "blue", "red")
expect(ab_user["link_color:1"]).to eq(alternative_name)
return_alternative_name = ab_test("link_color", "blue", "red")
expect(return_alternative_name).to eq(alternative_name)
end
it "should reset the session of a user on an older version of the experiment" do
alternative_name = ab_test("link_color", "blue", "red")
expect(ab_user["link_color"]).to eq(alternative_name)
alternative = Split::Alternative.new(alternative_name, "link_color")
expect(alternative.participant_count).to eq(1)
experiment.reset
expect(experiment.version).to eq(1)
alternative = Split::Alternative.new(alternative_name, "link_color")
expect(alternative.participant_count).to eq(0)
new_alternative_name = ab_test("link_color", "blue", "red")
expect(ab_user["link_color:1"]).to eq(new_alternative_name)
new_alternative = Split::Alternative.new(new_alternative_name, "link_color")
expect(new_alternative.participant_count).to eq(1)
end
it "should cleanup old versions of experiments from the session" do
alternative_name = ab_test("link_color", "blue", "red")
expect(ab_user["link_color"]).to eq(alternative_name)
alternative = Split::Alternative.new(alternative_name, "link_color")
expect(alternative.participant_count).to eq(1)
experiment.reset
expect(experiment.version).to eq(1)
alternative = Split::Alternative.new(alternative_name, "link_color")
expect(alternative.participant_count).to eq(0)
new_alternative_name = ab_test("link_color", "blue", "red")
expect(ab_user["link_color:1"]).to eq(new_alternative_name)
end
it "should only count completion of users on the current version" do
alternative_name = ab_test("link_color", "blue", "red")
expect(ab_user["link_color"]).to eq(alternative_name)
Split::Alternative.new(alternative_name, "link_color")
experiment.reset
expect(experiment.version).to eq(1)
ab_finished("link_color")
alternative = Split::Alternative.new(alternative_name, "link_color")
expect(alternative.completed_count).to eq(0)
end
end
context "when redis is not available" do
before(:each) do
expect(Split).to receive(:redis).at_most(5).times.and_raise(Errno::ECONNREFUSED.new)
end
context "and db_failover config option is turned off" do
before(:each) do
Split.configure do |config|
config.db_failover = false
end
end
describe "ab_test" do
it "should raise an exception" do
expect { ab_test("link_color", "blue", "red") }.to raise_error(Errno::ECONNREFUSED)
end
end
describe "finished" do
it "should raise an exception" do
expect { ab_finished("link_color") }.to raise_error(Errno::ECONNREFUSED)
end
end
describe "disable split testing" do
before(:each) do
Split.configure do |config|
config.enabled = false
end
end
it "should not attempt to connect to redis" do
expect { ab_test("link_color", "blue", "red") }.not_to raise_error
end
it "should return control variable" do
expect(ab_test("link_color", "blue", "red")).to eq("blue")
expect { ab_finished("link_color") }.not_to raise_error
end
end
end
context "and db_failover config option is turned on" do
before(:each) do
Split.configure do |config|
config.db_failover = true
end
end
describe "ab_test" do
it "should not raise an exception" do
expect { ab_test("link_color", "blue", "red") }.not_to raise_error
end
it "should call db_failover_on_db_error proc with error as parameter" do
Split.configure do |config|
config.db_failover_on_db_error = proc do |error|
expect(error).to be_a(Errno::ECONNREFUSED)
end
end
expect(Split.configuration.db_failover_on_db_error).to receive(:call).and_call_original
ab_test("link_color", "blue", "red")
end
it "should always use first alternative" do
expect(ab_test("link_color", "blue", "red")).to eq("blue")
expect(ab_test("link_color", { "blue" => 0.01 }, "red" => 0.2)).to eq("blue")
expect(ab_test("link_color", { "blue" => 0.8 }, { "red" => 20 })).to eq("blue")
expect(ab_test("link_color", "blue", "red") do |alternative|
"shared/#{alternative}"
end).to eq("shared/blue")
end
context "and db_failover_allow_parameter_override config option is turned on" do
before(:each) do
Split.configure do |config|
config.db_failover_allow_parameter_override = true
end
end
context "and given an override parameter" do
it "should use given override instead of the first alternative" do
@params = { "ab_test" => { "link_color" => "red" } }
expect(ab_test("link_color", "blue", "red")).to eq("red")
expect(ab_test("link_color", "blue", "red", "green")).to eq("red")
expect(ab_test("link_color", { "blue" => 0.01 }, "red" => 0.2)).to eq("red")
expect(ab_test("link_color", { "blue" => 0.8 }, { "red" => 20 })).to eq("red")
expect(ab_test("link_color", "blue", "red") do |alternative|
"shared/#{alternative}"
end).to eq("shared/red")
end
end
end
context "and preloaded config given" do
before do
Split.configuration.experiments[:link_color] = {
alternatives: [ "blue", "red" ],
}
end
it "uses first alternative" do
expect(ab_test(:link_color)).to eq("blue")
end
end
end
describe "finished" do
it "should not raise an exception" do
expect { ab_finished("link_color") }.not_to raise_error
end
it "should call db_failover_on_db_error proc with error as parameter" do
Split.configure do |config|
config.db_failover_on_db_error = proc do |error|
expect(error).to be_a(Errno::ECONNREFUSED)
end
end
expect(Split.configuration.db_failover_on_db_error).to receive(:call).and_call_original
ab_finished("link_color")
end
end
end
end
context "with preloaded config" do
before { Split.configuration.experiments = {} }
it "pulls options from config file" do
Split.configuration.experiments[:my_experiment] = {
alternatives: [ "control_opt", "other_opt" ],
goals: ["goal1", "goal2"]
}
ab_test :my_experiment
expect(Split::Experiment.new(:my_experiment).alternatives.map(&:name)).to eq([ "control_opt", "other_opt" ])
expect(Split::Experiment.new(:my_experiment).goals).to eq([ "goal1", "goal2" ])
end
it "can be called multiple times" do
Split.configuration.experiments[:my_experiment] = {
alternatives: [ "control_opt", "other_opt" ],
goals: ["goal1", "goal2"]
}
5.times { ab_test :my_experiment }
experiment = Split::Experiment.new(:my_experiment)
expect(experiment.alternatives.map(&:name)).to eq([ "control_opt", "other_opt" ])
expect(experiment.goals).to eq([ "goal1", "goal2" ])
expect(experiment.participant_count).to eq(1)
end
it "accepts multiple goals" do
Split.configuration.experiments[:my_experiment] = {
alternatives: [ "control_opt", "other_opt" ],
goals: [ "goal1", "goal2", "goal3" ]
}
ab_test :my_experiment
experiment = Split::Experiment.new(:my_experiment)
expect(experiment.goals).to eq([ "goal1", "goal2", "goal3" ])
end
it "allow specifying goals to be optional" do
Split.configuration.experiments[:my_experiment] = {
alternatives: [ "control_opt", "other_opt" ]
}
experiment = Split::Experiment.new(:my_experiment)
expect(experiment.goals).to eq([])
end
it "accepts multiple alternatives" do
Split.configuration.experiments[:my_experiment] = {
alternatives: [ "control_opt", "second_opt", "third_opt" ],
}
ab_test :my_experiment
experiment = Split::Experiment.new(:my_experiment)
expect(experiment.alternatives.map(&:name)).to eq([ "control_opt", "second_opt", "third_opt" ])
end
it "accepts probability on alternatives" do
Split.configuration.experiments[:my_experiment] = {
alternatives: [
{ name: "control_opt", percent: 67 },
{ name: "second_opt", percent: 10 },
{ name: "third_opt", percent: 23 },
],
}
ab_test :my_experiment
experiment = Split::Experiment.new(:my_experiment)
expect(experiment.alternatives.collect { |a| [a.name, a.weight] }).to eq([["control_opt", 0.67], ["second_opt", 0.1], ["third_opt", 0.23]])
end
it "accepts probability on some alternatives" do
Split.configuration.experiments[:my_experiment] = {
alternatives: [
{ name: "control_opt", percent: 34 },
"second_opt",
{ name: "third_opt", percent: 23 },
"fourth_opt",
],
}
ab_test :my_experiment
experiment = Split::Experiment.new(:my_experiment)
names_and_weights = experiment.alternatives.collect { |a| [a.name, a.weight] }
expect(names_and_weights).to eq([["control_opt", 0.34], ["second_opt", 0.215], ["third_opt", 0.23], ["fourth_opt", 0.215]])
expect(names_and_weights.inject(0) { |sum, nw| sum + nw[1] }).to eq(1.0)
end
it "allows name param without probability" do
Split.configuration.experiments[:my_experiment] = {
alternatives: [
{ name: "control_opt" },
"second_opt",
{ name: "third_opt", percent: 64 },
],
}
ab_test :my_experiment
experiment = Split::Experiment.new(:my_experiment)
names_and_weights = experiment.alternatives.collect { |a| [a.name, a.weight] }
expect(names_and_weights).to eq([["control_opt", 0.18], ["second_opt", 0.18], ["third_opt", 0.64]])
expect(names_and_weights.inject(0) { |sum, nw| sum + nw[1] }).to eq(1.0)
end
it "fails gracefully if config is missing experiment" do
Split.configuration.experiments = { other_experiment: { foo: "Bar" } }
expect { ab_test :my_experiment }.to raise_error(Split::ExperimentNotFound)
end
it "fails gracefully if config is missing" do
expect { Split.configuration.experiments = nil }.to raise_error(Split::InvalidExperimentsFormatError)
end
it "fails gracefully if config is missing alternatives" do
Split.configuration.experiments[:my_experiment] = { foo: "Bar" }
expect { ab_test :my_experiment }.to raise_error(NoMethodError)
end
end
it "should handle multiple experiments correctly" do
experiment2 = Split::ExperimentCatalog.find_or_create("link_color2", "blue", "red")
ab_test("link_color", "blue", "red")
ab_test("link_color2", "blue", "red")
ab_finished("link_color2")
experiment2.alternatives.each do |alt|
expect(alt.unfinished_count).to eq(0)
end
end
context "with goals" do
before do
@experiment = { "link_color" => ["purchase", "refund"] }
@alternatives = ["blue", "red"]
@experiment_name, @goals = normalize_metric(@experiment)
@goal1 = @goals[0]
@goal2 = @goals[1]
end
it "should normalize experiment" do
expect(@experiment_name).to eq("link_color")
expect(@goals).to eq(["purchase", "refund"])
end
describe "ab_test" do
it "should allow experiment goals interface as a single hash" do
ab_test(@experiment, *@alternatives)
experiment = Split::ExperimentCatalog.find("link_color")
expect(experiment.goals).to eq(["purchase", "refund"])
end
end
describe "ab_finished" do
before do
@alternative_name = ab_test(@experiment, *@alternatives)
end
it "should increment the counter for the specified-goal completed alternative" do
expect { ab_finished({ "link_color" => ["purchase"] }) }
.to change { Split::Alternative.new(@alternative_name, @experiment_name).completed_count(@goal2) }.by(0)
.and change { Split::Alternative.new(@alternative_name, @experiment_name).completed_count(@goal1) }.by(1)
end
end
end
end
<MSG> Merge pull request #263 from hwartig/option-to-disable-split
Provide an option to generically disable Split.
<DFF> @@ -113,6 +113,24 @@ describe Split::Helper do
ab_test('link_color', 'blue', 'red')
end
+ it "SPLIT_DISABLE query parameter should also force the alternative (uses control)" do
+ @params = {'SPLIT_DISABLE' => 'true'}
+ alternative = ab_test('link_color', 'blue', 'red')
+ alternative.should eql('blue')
+ alternative = ab_test('link_color', {'blue' => 1}, 'red' => 5)
+ alternative.should eql('blue')
+ alternative = ab_test('link_color', 'red', 'blue')
+ alternative.should eql('red')
+ alternative = ab_test('link_color', {'red' => 5}, 'blue' => 1)
+ alternative.should eql('red')
+ end
+
+ it "should not store the split when Split generically disabled" do
+ @params = {'SPLIT_DISABLE' => 'true'}
+ ab_user.should_not_receive(:[]=)
+ ab_test('link_color', 'blue', 'red')
+ end
+
context "when store_override is set" do
before { Split.configuration.store_override = true }
| 18 | Merge pull request #263 from hwartig/option-to-disable-split | 0 | .rb | rb | mit | splitrb/split |
10071948 | <NME> helper_spec.rb
<BEF> # frozen_string_literal: true
require "spec_helper"
# TODO change some of these tests to use Rack::Test
describe Split::Helper do
include Split::Helper
let(:experiment) {
Split::ExperimentCatalog.find_or_create("link_color", "blue", "red")
}
describe "ab_test" do
it "should not raise an error when passed strings for alternatives" do
expect { ab_test("xyz", "1", "2", "3") }.not_to raise_error
end
it "should not raise an error when passed an array for alternatives" do
expect { ab_test("xyz", ["1", "2", "3"]) }.not_to raise_error
end
it "should raise the appropriate error when passed integers for alternatives" do
expect { ab_test("xyz", 1, 2, 3) }.to raise_error(ArgumentError)
end
it "should raise the appropriate error when passed symbols for alternatives" do
expect { ab_test("xyz", :a, :b, :c) }.to raise_error(ArgumentError)
end
it "should not raise error when passed an array for goals" do
expect { ab_test({ "link_color" => ["purchase", "refund"] }, "blue", "red") }.not_to raise_error
end
it "should not raise error when passed just one goal" do
expect { ab_test({ "link_color" => "purchase" }, "blue", "red") }.not_to raise_error
end
it "raises an appropriate error when processing combined expirements" do
Split.configuration.experiments = {
combined_exp_1: {
alternatives: [ { name: "control", percent: 50 }, { name: "test-alt", percent: 50 } ],
metric: :my_metric,
combined_experiments: [:combined_exp_1_sub_1]
}
}
Split::ExperimentCatalog.find_or_create("combined_exp_1")
expect { ab_test("combined_exp_1") }.to raise_error(Split::InvalidExperimentsFormatError)
end
it "should assign a random alternative to a new user when there are an equal number of alternatives assigned" do
ab_test("link_color", "blue", "red")
expect(["red", "blue"]).to include(ab_user["link_color"])
end
it "should increment the participation counter after assignment to a new user" do
previous_red_count = Split::Alternative.new("red", "link_color").participant_count
previous_blue_count = Split::Alternative.new("blue", "link_color").participant_count
ab_test("link_color", "blue", "red")
new_red_count = Split::Alternative.new("red", "link_color").participant_count
new_blue_count = Split::Alternative.new("blue", "link_color").participant_count
expect((new_red_count + new_blue_count)).to eq(previous_red_count + previous_blue_count + 1)
end
it "should not increment the counter for an experiment that the user is not participating in" do
ab_test("link_color", "blue", "red")
e = Split::ExperimentCatalog.find_or_create("button_size", "small", "big")
expect {
# User shouldn't participate in this second experiment
ab_test("button_size", "small", "big")
}.not_to change { e.participant_count }
end
it "should not increment the counter for an ended experiment" do
e = Split::ExperimentCatalog.find_or_create("button_size", "small", "big")
e.winner = "small"
expect {
a = ab_test("button_size", "small", "big")
expect(a).to eq("small")
}.not_to change { e.participant_count }
end
it "should not increment the counter for an not started experiment" do
expect(Split.configuration).to receive(:start_manually).and_return(true)
e = Split::ExperimentCatalog.find_or_create("button_size", "small", "big")
expect {
a = ab_test("button_size", "small", "big")
expect(a).to eq("small")
}.not_to change { e.participant_count }
end
it "should return the given alternative for an existing user" do
expect(ab_test("link_color", "blue", "red")).to eq ab_test("link_color", "blue", "red")
end
it "should always return the winner if one is present" do
experiment.winner = "orange"
expect(ab_test("link_color", "blue", "red")).to eq("orange")
end
it "should allow the alternative to be forced by passing it in the params" do
# ?ab_test[link_color]=blue
@params = { "ab_test" => { "link_color" => "blue" } }
alternative = ab_test("link_color", "blue", "red")
expect(alternative).to eq("blue")
alternative = ab_test("link_color", { "blue" => 1 }, "red" => 5)
ab_test('link_color', 'blue', 'red')
end
context "when store_override is set" do
before { Split.configuration.store_override = true }
@params = { "SPLIT_DISABLE" => "true" }
alternative = ab_test("link_color", "blue", "red")
expect(alternative).to eq("blue")
alternative = ab_test("link_color", { "blue" => 1 }, "red" => 5)
expect(alternative).to eq("blue")
alternative = ab_test("link_color", "red", "blue")
expect(alternative).to eq("red")
alternative = ab_test("link_color", { "red" => 5 }, "blue" => 1)
expect(alternative).to eq("red")
end
it "should not store the split when Split generically disabled" do
@params = { "SPLIT_DISABLE" => "true" }
expect(ab_user).not_to receive(:[]=)
ab_test("link_color", "blue", "red")
end
context "when store_override is set" do
before { Split.configuration.store_override = true }
it "should store the forced alternative" do
@params = { "ab_test" => { "link_color" => "blue" } }
expect(ab_user).to receive(:[]=).with("link_color", "blue")
ab_test("link_color", "blue", "red")
end
end
context "when on_trial_choose is set" do
before { Split.configuration.on_trial_choose = :some_method }
it "should call the method" do
expect(self).to receive(:some_method)
ab_test("link_color", "blue", "red")
end
end
it "should allow passing a block" do
alt = ab_test("link_color", "blue", "red")
ret = ab_test("link_color", "blue", "red") { |alternative| "shared/#{alternative}" }
expect(ret).to eq("shared/#{alt}")
end
it "should allow the share of visitors see an alternative to be specified" do
ab_test("link_color", { "blue" => 0.8 }, { "red" => 20 })
expect(["red", "blue"]).to include(ab_user["link_color"])
end
it "should allow alternative weighting interface as a single hash" do
ab_test("link_color", { "blue" => 0.01 }, "red" => 0.2)
experiment = Split::ExperimentCatalog.find("link_color")
expect(experiment.alternatives.map(&:name)).to eq(["blue", "red"])
expect(experiment.alternatives.collect { |a| a.weight }).to match_array([0.01, 0.2])
end
it "should only let a user participate in one experiment at a time" do
link_color = ab_test("link_color", "blue", "red")
ab_test("button_size", "small", "big")
expect(ab_user["link_color"]).to eq(link_color)
big = Split::Alternative.new("big", "button_size")
expect(big.participant_count).to eq(0)
small = Split::Alternative.new("small", "button_size")
expect(small.participant_count).to eq(0)
end
it "should let a user participate in many experiment with allow_multiple_experiments option" do
Split.configure do |config|
config.allow_multiple_experiments = true
end
link_color = ab_test("link_color", "blue", "red")
button_size = ab_test("button_size", "small", "big")
expect(ab_user["link_color"]).to eq(link_color)
expect(ab_user["button_size"]).to eq(button_size)
button_size_alt = Split::Alternative.new(button_size, "button_size")
expect(button_size_alt.participant_count).to eq(1)
end
context "with allow_multiple_experiments = 'control'" do
it "should let a user participate in many experiment with one non-'control' alternative" do
Split.configure do |config|
config.allow_multiple_experiments = "control"
end
groups = 100.times.map do |n|
ab_test("test#{n}".to_sym, { "control" => (100 - n) }, { "test#{n}-alt" => n })
end
experiments = ab_user.active_experiments
expect(experiments.size).to be > 1
count_control = experiments.values.count { |g| g == "control" }
expect(count_control).to eq(experiments.size - 1)
count_alts = groups.count { |g| g != "control" }
expect(count_alts).to eq(1)
end
context "when user already has experiment" do
let(:mock_user) { Split::User.new(self, { "test_0" => "test-alt" }) }
before do
Split.configure do |config|
config.allow_multiple_experiments = "control"
end
Split::ExperimentCatalog.find_or_initialize("test_0", "control", "test-alt").save
Split::ExperimentCatalog.find_or_initialize("test_1", "control", "test-alt").save
end
it "should restore previously selected alternative" do
expect(ab_user.active_experiments.size).to eq 1
expect(ab_test(:test_0, { "control" => 100 }, { "test-alt" => 1 })).to eq "test-alt"
expect(ab_test(:test_0, { "control" => 1 }, { "test-alt" => 100 })).to eq "test-alt"
end
it "should select the correct alternatives after experiment resets" do
experiment = Split::ExperimentCatalog.find(:test_0)
experiment.reset
mock_user[experiment.key] = "test-alt"
expect(ab_user.active_experiments.size).to eq 1
expect(ab_test(:test_0, { "control" => 100 }, { "test-alt" => 1 })).to eq "test-alt"
expect(ab_test(:test_0, { "control" => 0 }, { "test-alt" => 100 })).to eq "test-alt"
end
it "lets override existing choice" do
pending "this requires user store reset on first call not depending on whelther it is current trial"
@params = { "ab_test" => { "test_1" => "test-alt" } }
expect(ab_test(:test_0, { "control" => 0 }, { "test-alt" => 100 })).to eq "control"
expect(ab_test(:test_1, { "control" => 100 }, { "test-alt" => 1 })).to eq "test-alt"
end
end
end
it "should not over-write a finished key when an experiment is on a later version" do
experiment.increment_version
ab_user = { experiment.key => "blue", experiment.finished_key => true }
finished_session = ab_user.dup
ab_test("link_color", "blue", "red")
expect(ab_user).to eq(finished_session)
end
end
describe "metadata" do
context "is defined" do
before do
Split.configuration.experiments = {
my_experiment: {
alternatives: ["one", "two"],
resettable: false,
metadata: { "one" => "Meta1", "two" => "Meta2" }
}
}
end
it "should be passed to helper block" do
@params = { "ab_test" => { "my_experiment" => "two" } }
expect(ab_test("my_experiment")).to eq "two"
expect(ab_test("my_experiment") do |alternative, meta|
meta
end).to eq("Meta2")
end
it "should pass control metadata helper block if library disabled" do
Split.configure do |config|
config.enabled = false
end
expect(ab_test("my_experiment")).to eq "one"
expect(ab_test("my_experiment") do |_, meta|
meta
end).to eq("Meta1")
end
end
context "is not defined" do
before do
Split.configuration.experiments = {
my_experiment: {
alternatives: ["one", "two"],
resettable: false,
metadata: nil
}
}
end
it "should be passed to helper block" do
expect(ab_test("my_experiment") do |alternative, meta|
meta
end).to eq({})
end
it "should pass control metadata helper block if library disabled" do
Split.configure do |config|
config.enabled = false
end
expect(ab_test("my_experiment") do |_, meta|
meta
end).to eq({})
end
end
end
describe "ab_finished" do
context "for an experiment that the user participates in" do
before(:each) do
@experiment_name = "link_color"
@alternatives = ["blue", "red"]
@experiment = Split::ExperimentCatalog.find_or_create(@experiment_name, *@alternatives)
@alternative_name = ab_test(@experiment_name, *@alternatives)
@previous_completion_count = Split::Alternative.new(@alternative_name, @experiment_name).completed_count
end
it "should increment the counter for the completed alternative" do
ab_finished(@experiment_name)
new_completion_count = Split::Alternative.new(@alternative_name, @experiment_name).completed_count
expect(new_completion_count).to eq(@previous_completion_count + 1)
end
it "should set experiment's finished key if reset is false" do
ab_finished(@experiment_name, { reset: false })
expect(ab_user[@experiment.key]).to eq(@alternative_name)
expect(ab_user[@experiment.finished_key]).to eq(true)
end
it "should not increment the counter if reset is false and the experiment has been already finished" do
2.times { ab_finished(@experiment_name, { reset: false }) }
new_completion_count = Split::Alternative.new(@alternative_name, @experiment_name).completed_count
expect(new_completion_count).to eq(@previous_completion_count + 1)
end
it "should not increment the counter for an ended experiment" do
e = Split::ExperimentCatalog.find_or_create("button_size", "small", "big")
e.winner = "small"
a = ab_test("button_size", "small", "big")
expect(a).to eq("small")
expect {
ab_finished("button_size")
}.not_to change { Split::Alternative.new(a, "button_size").completed_count }
end
it "should clear out the user's participation from their session" do
expect(ab_user[@experiment.key]).to eq(@alternative_name)
ab_finished(@experiment_name)
expect(ab_user.keys).to be_empty
end
it "should not clear out the users session if reset is false" do
expect(ab_user[@experiment.key]).to eq(@alternative_name)
ab_finished(@experiment_name, { reset: false })
expect(ab_user[@experiment.key]).to eq(@alternative_name)
expect(ab_user[@experiment.finished_key]).to eq(true)
end
it "should reset the users session when experiment is not versioned" do
expect(ab_user[@experiment.key]).to eq(@alternative_name)
ab_finished(@experiment_name)
expect(ab_user.keys).to be_empty
end
it "should reset the users session when experiment is versioned" do
@experiment.increment_version
@alternative_name = ab_test(@experiment_name, *@alternatives)
expect(ab_user[@experiment.key]).to eq(@alternative_name)
ab_finished(@experiment_name)
expect(ab_user.keys).to be_empty
end
context "when on_trial_complete is set" do
before { Split.configuration.on_trial_complete = :some_method }
it "should call the method" do
expect(self).to receive(:some_method)
ab_finished(@experiment_name)
end
it "should not call the method without alternative" do
ab_user[@experiment.key] = nil
expect(self).not_to receive(:some_method)
ab_finished(@experiment_name)
end
end
end
context "for an experiment that the user is excluded from" do
before do
alternative = ab_test("link_color", "blue", "red")
expect(Split::Alternative.new(alternative, "link_color").participant_count).to eq(1)
alternative = ab_test("button_size", "small", "big")
expect(Split::Alternative.new(alternative, "button_size").participant_count).to eq(0)
end
it "should not increment the completed counter" do
# So, user should be participating in the link_color experiment and
# receive the control for button_size. As the user is not participating in
# the button size experiment, finishing it should not increase the
# completion count for that alternative.
expect {
ab_finished("button_size")
}.not_to change { Split::Alternative.new("small", "button_size").completed_count }
end
end
context "for an experiment that the user does not participate in" do
before do
Split::ExperimentCatalog.find_or_create(:not_started_experiment, "control", "alt")
end
it "should not raise an exception" do
expect { ab_finished(:not_started_experiment) }.not_to raise_exception
end
it "should not change the user state when reset is false" do
expect { ab_finished(:not_started_experiment, reset: false) }.not_to change { ab_user.keys }.from([])
end
it "should not change the user state when reset is true" do
expect(self).not_to receive(:reset!)
ab_finished(:not_started_experiment)
end
it "should not increment the completed counter" do
ab_finished(:not_started_experiment)
expect(Split::Alternative.new("control", :not_started_experiment).completed_count).to eq(0)
expect(Split::Alternative.new("alt", :not_started_experiment).completed_count).to eq(0)
end
end
end
context "finished with config" do
it "passes reset option" do
Split.configuration.experiments = {
my_experiment: {
alternatives: ["one", "two"],
resettable: false,
}
}
alternative = ab_test(:my_experiment)
experiment = Split::ExperimentCatalog.find :my_experiment
ab_finished :my_experiment
expect(ab_user[experiment.key]).to eq(alternative)
expect(ab_user[experiment.finished_key]).to eq(true)
end
end
context "finished with metric name" do
before { Split.configuration.experiments = {} }
before { expect(Split::Alternative).to receive(:new).at_least(1).times.and_call_original }
def should_finish_experiment(experiment_name, should_finish = true)
alts = Split.configuration.experiments[experiment_name][:alternatives]
experiment = Split::ExperimentCatalog.find_or_create(experiment_name, *alts)
alt_name = ab_user[experiment.key] = alts.first
alt = double("alternative")
expect(alt).to receive(:name).at_most(1).times.and_return(alt_name)
expect(Split::Alternative).to receive(:new).at_most(1).times.with(alt_name, experiment_name.to_s).and_return(alt)
if should_finish
expect(alt).to receive(:increment_completion).at_most(1).times
else
expect(alt).not_to receive(:increment_completion)
end
end
it "completes the test" do
Split.configuration.experiments[:my_experiment] = {
alternatives: [ "control_opt", "other_opt" ],
metric: :my_metric
}
should_finish_experiment :my_experiment
ab_finished :my_metric
end
it "completes all relevant tests" do
Split.configuration.experiments = {
exp_1: {
alternatives: [ "1-1", "1-2" ],
metric: :my_metric
},
exp_2: {
alternatives: [ "2-1", "2-2" ],
metric: :another_metric
},
exp_3: {
alternatives: [ "3-1", "3-2" ],
metric: :my_metric
},
}
should_finish_experiment :exp_1
should_finish_experiment :exp_2, false
should_finish_experiment :exp_3
ab_finished :my_metric
end
it "passes reset option" do
Split.configuration.experiments = {
my_exp: {
alternatives: ["one", "two"],
metric: :my_metric,
resettable: false,
}
}
alternative_name = ab_test(:my_exp)
exp = Split::ExperimentCatalog.find :my_exp
ab_finished :my_metric
expect(ab_user[exp.key]).to eq(alternative_name)
expect(ab_user[exp.finished_key]).to be_truthy
end
it "passes through options" do
Split.configuration.experiments = {
my_exp: {
alternatives: ["one", "two"],
metric: :my_metric,
}
}
alternative_name = ab_test(:my_exp)
exp = Split::ExperimentCatalog.find :my_exp
ab_finished :my_metric, reset: false
expect(ab_user[exp.key]).to eq(alternative_name)
expect(ab_user[exp.finished_key]).to be_truthy
end
end
describe "conversions" do
it "should return a conversion rate for an alternative" do
alternative_name = ab_test("link_color", "blue", "red")
previous_convertion_rate = Split::Alternative.new(alternative_name, "link_color").conversion_rate
expect(previous_convertion_rate).to eq(0.0)
ab_finished("link_color")
new_convertion_rate = Split::Alternative.new(alternative_name, "link_color").conversion_rate
expect(new_convertion_rate).to eq(1.0)
end
end
describe "active experiments" do
it "should show an active test" do
alternative = ab_test("def", "4", "5", "6")
expect(active_experiments.count).to eq 1
expect(active_experiments.first[0]).to eq "def"
expect(active_experiments.first[1]).to eq alternative
end
it "should show a finished test" do
alternative = ab_test("def", "4", "5", "6")
ab_finished("def", { reset: false })
expect(active_experiments.count).to eq 1
expect(active_experiments.first[0]).to eq "def"
expect(active_experiments.first[1]).to eq alternative
end
it "should show an active test when an experiment is on a later version" do
experiment.reset
expect(experiment.version).to eq(1)
ab_test("link_color", "blue", "red")
expect(active_experiments.count).to eq 1
expect(active_experiments.first[0]).to eq "link_color"
end
it "should show versioned tests properly" do
10.times { experiment.reset }
alternative = ab_test(experiment.name, "blue", "red")
ab_finished(experiment.name, reset: false)
expect(experiment.version).to eq(10)
expect(active_experiments.count).to eq 1
expect(active_experiments).to eq({ "link_color" => alternative })
end
it "should show multiple tests" do
Split.configure do |config|
config.allow_multiple_experiments = true
end
alternative = ab_test("def", "4", "5", "6")
another_alternative = ab_test("ghi", "7", "8", "9")
expect(active_experiments.count).to eq 2
expect(active_experiments["def"]).to eq alternative
expect(active_experiments["ghi"]).to eq another_alternative
end
it "should not show tests with winners" do
Split.configure do |config|
config.allow_multiple_experiments = true
end
e = Split::ExperimentCatalog.find_or_create("def", "4", "5", "6")
e.winner = "4"
ab_test("def", "4", "5", "6")
another_alternative = ab_test("ghi", "7", "8", "9")
expect(active_experiments.count).to eq 1
expect(active_experiments.first[0]).to eq "ghi"
expect(active_experiments.first[1]).to eq another_alternative
end
end
describe "when user is a robot" do
before(:each) do
@request = OpenStruct.new(user_agent: "Googlebot/2.1 (+http://www.google.com/bot.html)")
end
describe "ab_test" do
it "should return the control" do
alternative = ab_test("link_color", "blue", "red")
expect(alternative).to eq experiment.control.name
end
it "should not create a experiment" do
ab_test("link_color", "blue", "red")
expect(Split::Experiment.new("link_color")).to be_a_new_record
end
it "should not increment the participation count" do
previous_red_count = Split::Alternative.new("red", "link_color").participant_count
previous_blue_count = Split::Alternative.new("blue", "link_color").participant_count
ab_test("link_color", "blue", "red")
new_red_count = Split::Alternative.new("red", "link_color").participant_count
new_blue_count = Split::Alternative.new("blue", "link_color").participant_count
expect((new_red_count + new_blue_count)).to eq(previous_red_count + previous_blue_count)
end
end
describe "finished" do
it "should not increment the completed count" do
alternative_name = ab_test("link_color", "blue", "red")
previous_completion_count = Split::Alternative.new(alternative_name, "link_color").completed_count
ab_finished("link_color")
new_completion_count = Split::Alternative.new(alternative_name, "link_color").completed_count
expect(new_completion_count).to eq(previous_completion_count)
end
end
end
describe "when providing custom ignore logic" do
context "using a proc to configure custom logic" do
before(:each) do
Split.configure do |c|
c.ignore_filter = proc { |request| true } # ignore everything
end
end
it "ignores the ab_test" do
ab_test("link_color", "blue", "red")
red_count = Split::Alternative.new("red", "link_color").participant_count
blue_count = Split::Alternative.new("blue", "link_color").participant_count
expect((red_count + blue_count)).to be(0)
end
end
end
shared_examples_for "a disabled test" do
describe "ab_test" do
it "should return the control" do
alternative = ab_test("link_color", "blue", "red")
expect(alternative).to eq experiment.control.name
end
it "should not increment the participation count" do
previous_red_count = Split::Alternative.new("red", "link_color").participant_count
previous_blue_count = Split::Alternative.new("blue", "link_color").participant_count
ab_test("link_color", "blue", "red")
new_red_count = Split::Alternative.new("red", "link_color").participant_count
new_blue_count = Split::Alternative.new("blue", "link_color").participant_count
expect((new_red_count + new_blue_count)).to eq(previous_red_count + previous_blue_count)
end
end
describe "finished" do
it "should not increment the completed count" do
alternative_name = ab_test("link_color", "blue", "red")
previous_completion_count = Split::Alternative.new(alternative_name, "link_color").completed_count
ab_finished("link_color")
new_completion_count = Split::Alternative.new(alternative_name, "link_color").completed_count
expect(new_completion_count).to eq(previous_completion_count)
end
end
end
describe "when ip address is ignored" do
context "individually" do
before(:each) do
@request = OpenStruct.new(ip: "81.19.48.130")
Split.configure do |c|
c.ignore_ip_addresses << "81.19.48.130"
end
end
it_behaves_like "a disabled test"
end
context "for a range" do
before(:each) do
@request = OpenStruct.new(ip: "81.19.48.129")
Split.configure do |c|
c.ignore_ip_addresses << /81\.19\.48\.[0-9]+/
end
end
it_behaves_like "a disabled test"
end
context "using both a range and a specific value" do
before(:each) do
@request = OpenStruct.new(ip: "81.19.48.128")
Split.configure do |c|
c.ignore_ip_addresses << "81.19.48.130"
c.ignore_ip_addresses << /81\.19\.48\.[0-9]+/
end
end
it_behaves_like "a disabled test"
end
context "when ignored other address" do
before do
@request = OpenStruct.new(ip: "1.1.1.1")
Split.configure do |c|
c.ignore_ip_addresses << "81.19.48.130"
end
end
it "works as usual" do
alternative_name = ab_test("link_color", "red", "blue")
expect {
ab_finished("link_color")
}.to change(Split::Alternative.new(alternative_name, "link_color"), :completed_count).by(1)
end
end
end
describe "when user is previewing" do
before(:each) do
@request = OpenStruct.new(headers: { "x-purpose" => "preview" })
end
it_behaves_like "a disabled test"
end
describe "versioned experiments" do
it "should use version zero if no version is present" do
alternative_name = ab_test("link_color", "blue", "red")
expect(experiment.version).to eq(0)
expect(ab_user["link_color"]).to eq(alternative_name)
end
it "should save the version of the experiment to the session" do
experiment.reset
expect(experiment.version).to eq(1)
alternative_name = ab_test("link_color", "blue", "red")
expect(ab_user["link_color:1"]).to eq(alternative_name)
end
it "should load the experiment even if the version is not 0" do
experiment.reset
expect(experiment.version).to eq(1)
alternative_name = ab_test("link_color", "blue", "red")
expect(ab_user["link_color:1"]).to eq(alternative_name)
return_alternative_name = ab_test("link_color", "blue", "red")
expect(return_alternative_name).to eq(alternative_name)
end
it "should reset the session of a user on an older version of the experiment" do
alternative_name = ab_test("link_color", "blue", "red")
expect(ab_user["link_color"]).to eq(alternative_name)
alternative = Split::Alternative.new(alternative_name, "link_color")
expect(alternative.participant_count).to eq(1)
experiment.reset
expect(experiment.version).to eq(1)
alternative = Split::Alternative.new(alternative_name, "link_color")
expect(alternative.participant_count).to eq(0)
new_alternative_name = ab_test("link_color", "blue", "red")
expect(ab_user["link_color:1"]).to eq(new_alternative_name)
new_alternative = Split::Alternative.new(new_alternative_name, "link_color")
expect(new_alternative.participant_count).to eq(1)
end
it "should cleanup old versions of experiments from the session" do
alternative_name = ab_test("link_color", "blue", "red")
expect(ab_user["link_color"]).to eq(alternative_name)
alternative = Split::Alternative.new(alternative_name, "link_color")
expect(alternative.participant_count).to eq(1)
experiment.reset
expect(experiment.version).to eq(1)
alternative = Split::Alternative.new(alternative_name, "link_color")
expect(alternative.participant_count).to eq(0)
new_alternative_name = ab_test("link_color", "blue", "red")
expect(ab_user["link_color:1"]).to eq(new_alternative_name)
end
it "should only count completion of users on the current version" do
alternative_name = ab_test("link_color", "blue", "red")
expect(ab_user["link_color"]).to eq(alternative_name)
Split::Alternative.new(alternative_name, "link_color")
experiment.reset
expect(experiment.version).to eq(1)
ab_finished("link_color")
alternative = Split::Alternative.new(alternative_name, "link_color")
expect(alternative.completed_count).to eq(0)
end
end
context "when redis is not available" do
before(:each) do
expect(Split).to receive(:redis).at_most(5).times.and_raise(Errno::ECONNREFUSED.new)
end
context "and db_failover config option is turned off" do
before(:each) do
Split.configure do |config|
config.db_failover = false
end
end
describe "ab_test" do
it "should raise an exception" do
expect { ab_test("link_color", "blue", "red") }.to raise_error(Errno::ECONNREFUSED)
end
end
describe "finished" do
it "should raise an exception" do
expect { ab_finished("link_color") }.to raise_error(Errno::ECONNREFUSED)
end
end
describe "disable split testing" do
before(:each) do
Split.configure do |config|
config.enabled = false
end
end
it "should not attempt to connect to redis" do
expect { ab_test("link_color", "blue", "red") }.not_to raise_error
end
it "should return control variable" do
expect(ab_test("link_color", "blue", "red")).to eq("blue")
expect { ab_finished("link_color") }.not_to raise_error
end
end
end
context "and db_failover config option is turned on" do
before(:each) do
Split.configure do |config|
config.db_failover = true
end
end
describe "ab_test" do
it "should not raise an exception" do
expect { ab_test("link_color", "blue", "red") }.not_to raise_error
end
it "should call db_failover_on_db_error proc with error as parameter" do
Split.configure do |config|
config.db_failover_on_db_error = proc do |error|
expect(error).to be_a(Errno::ECONNREFUSED)
end
end
expect(Split.configuration.db_failover_on_db_error).to receive(:call).and_call_original
ab_test("link_color", "blue", "red")
end
it "should always use first alternative" do
expect(ab_test("link_color", "blue", "red")).to eq("blue")
expect(ab_test("link_color", { "blue" => 0.01 }, "red" => 0.2)).to eq("blue")
expect(ab_test("link_color", { "blue" => 0.8 }, { "red" => 20 })).to eq("blue")
expect(ab_test("link_color", "blue", "red") do |alternative|
"shared/#{alternative}"
end).to eq("shared/blue")
end
context "and db_failover_allow_parameter_override config option is turned on" do
before(:each) do
Split.configure do |config|
config.db_failover_allow_parameter_override = true
end
end
context "and given an override parameter" do
it "should use given override instead of the first alternative" do
@params = { "ab_test" => { "link_color" => "red" } }
expect(ab_test("link_color", "blue", "red")).to eq("red")
expect(ab_test("link_color", "blue", "red", "green")).to eq("red")
expect(ab_test("link_color", { "blue" => 0.01 }, "red" => 0.2)).to eq("red")
expect(ab_test("link_color", { "blue" => 0.8 }, { "red" => 20 })).to eq("red")
expect(ab_test("link_color", "blue", "red") do |alternative|
"shared/#{alternative}"
end).to eq("shared/red")
end
end
end
context "and preloaded config given" do
before do
Split.configuration.experiments[:link_color] = {
alternatives: [ "blue", "red" ],
}
end
it "uses first alternative" do
expect(ab_test(:link_color)).to eq("blue")
end
end
end
describe "finished" do
it "should not raise an exception" do
expect { ab_finished("link_color") }.not_to raise_error
end
it "should call db_failover_on_db_error proc with error as parameter" do
Split.configure do |config|
config.db_failover_on_db_error = proc do |error|
expect(error).to be_a(Errno::ECONNREFUSED)
end
end
expect(Split.configuration.db_failover_on_db_error).to receive(:call).and_call_original
ab_finished("link_color")
end
end
end
end
context "with preloaded config" do
before { Split.configuration.experiments = {} }
it "pulls options from config file" do
Split.configuration.experiments[:my_experiment] = {
alternatives: [ "control_opt", "other_opt" ],
goals: ["goal1", "goal2"]
}
ab_test :my_experiment
expect(Split::Experiment.new(:my_experiment).alternatives.map(&:name)).to eq([ "control_opt", "other_opt" ])
expect(Split::Experiment.new(:my_experiment).goals).to eq([ "goal1", "goal2" ])
end
it "can be called multiple times" do
Split.configuration.experiments[:my_experiment] = {
alternatives: [ "control_opt", "other_opt" ],
goals: ["goal1", "goal2"]
}
5.times { ab_test :my_experiment }
experiment = Split::Experiment.new(:my_experiment)
expect(experiment.alternatives.map(&:name)).to eq([ "control_opt", "other_opt" ])
expect(experiment.goals).to eq([ "goal1", "goal2" ])
expect(experiment.participant_count).to eq(1)
end
it "accepts multiple goals" do
Split.configuration.experiments[:my_experiment] = {
alternatives: [ "control_opt", "other_opt" ],
goals: [ "goal1", "goal2", "goal3" ]
}
ab_test :my_experiment
experiment = Split::Experiment.new(:my_experiment)
expect(experiment.goals).to eq([ "goal1", "goal2", "goal3" ])
end
it "allow specifying goals to be optional" do
Split.configuration.experiments[:my_experiment] = {
alternatives: [ "control_opt", "other_opt" ]
}
experiment = Split::Experiment.new(:my_experiment)
expect(experiment.goals).to eq([])
end
it "accepts multiple alternatives" do
Split.configuration.experiments[:my_experiment] = {
alternatives: [ "control_opt", "second_opt", "third_opt" ],
}
ab_test :my_experiment
experiment = Split::Experiment.new(:my_experiment)
expect(experiment.alternatives.map(&:name)).to eq([ "control_opt", "second_opt", "third_opt" ])
end
it "accepts probability on alternatives" do
Split.configuration.experiments[:my_experiment] = {
alternatives: [
{ name: "control_opt", percent: 67 },
{ name: "second_opt", percent: 10 },
{ name: "third_opt", percent: 23 },
],
}
ab_test :my_experiment
experiment = Split::Experiment.new(:my_experiment)
expect(experiment.alternatives.collect { |a| [a.name, a.weight] }).to eq([["control_opt", 0.67], ["second_opt", 0.1], ["third_opt", 0.23]])
end
it "accepts probability on some alternatives" do
Split.configuration.experiments[:my_experiment] = {
alternatives: [
{ name: "control_opt", percent: 34 },
"second_opt",
{ name: "third_opt", percent: 23 },
"fourth_opt",
],
}
ab_test :my_experiment
experiment = Split::Experiment.new(:my_experiment)
names_and_weights = experiment.alternatives.collect { |a| [a.name, a.weight] }
expect(names_and_weights).to eq([["control_opt", 0.34], ["second_opt", 0.215], ["third_opt", 0.23], ["fourth_opt", 0.215]])
expect(names_and_weights.inject(0) { |sum, nw| sum + nw[1] }).to eq(1.0)
end
it "allows name param without probability" do
Split.configuration.experiments[:my_experiment] = {
alternatives: [
{ name: "control_opt" },
"second_opt",
{ name: "third_opt", percent: 64 },
],
}
ab_test :my_experiment
experiment = Split::Experiment.new(:my_experiment)
names_and_weights = experiment.alternatives.collect { |a| [a.name, a.weight] }
expect(names_and_weights).to eq([["control_opt", 0.18], ["second_opt", 0.18], ["third_opt", 0.64]])
expect(names_and_weights.inject(0) { |sum, nw| sum + nw[1] }).to eq(1.0)
end
it "fails gracefully if config is missing experiment" do
Split.configuration.experiments = { other_experiment: { foo: "Bar" } }
expect { ab_test :my_experiment }.to raise_error(Split::ExperimentNotFound)
end
it "fails gracefully if config is missing" do
expect { Split.configuration.experiments = nil }.to raise_error(Split::InvalidExperimentsFormatError)
end
it "fails gracefully if config is missing alternatives" do
Split.configuration.experiments[:my_experiment] = { foo: "Bar" }
expect { ab_test :my_experiment }.to raise_error(NoMethodError)
end
end
it "should handle multiple experiments correctly" do
experiment2 = Split::ExperimentCatalog.find_or_create("link_color2", "blue", "red")
ab_test("link_color", "blue", "red")
ab_test("link_color2", "blue", "red")
ab_finished("link_color2")
experiment2.alternatives.each do |alt|
expect(alt.unfinished_count).to eq(0)
end
end
context "with goals" do
before do
@experiment = { "link_color" => ["purchase", "refund"] }
@alternatives = ["blue", "red"]
@experiment_name, @goals = normalize_metric(@experiment)
@goal1 = @goals[0]
@goal2 = @goals[1]
end
it "should normalize experiment" do
expect(@experiment_name).to eq("link_color")
expect(@goals).to eq(["purchase", "refund"])
end
describe "ab_test" do
it "should allow experiment goals interface as a single hash" do
ab_test(@experiment, *@alternatives)
experiment = Split::ExperimentCatalog.find("link_color")
expect(experiment.goals).to eq(["purchase", "refund"])
end
end
describe "ab_finished" do
before do
@alternative_name = ab_test(@experiment, *@alternatives)
end
it "should increment the counter for the specified-goal completed alternative" do
expect { ab_finished({ "link_color" => ["purchase"] }) }
.to change { Split::Alternative.new(@alternative_name, @experiment_name).completed_count(@goal2) }.by(0)
.and change { Split::Alternative.new(@alternative_name, @experiment_name).completed_count(@goal1) }.by(1)
end
end
end
end
<MSG> Merge pull request #263 from hwartig/option-to-disable-split
Provide an option to generically disable Split.
<DFF> @@ -113,6 +113,24 @@ describe Split::Helper do
ab_test('link_color', 'blue', 'red')
end
+ it "SPLIT_DISABLE query parameter should also force the alternative (uses control)" do
+ @params = {'SPLIT_DISABLE' => 'true'}
+ alternative = ab_test('link_color', 'blue', 'red')
+ alternative.should eql('blue')
+ alternative = ab_test('link_color', {'blue' => 1}, 'red' => 5)
+ alternative.should eql('blue')
+ alternative = ab_test('link_color', 'red', 'blue')
+ alternative.should eql('red')
+ alternative = ab_test('link_color', {'red' => 5}, 'blue' => 1)
+ alternative.should eql('red')
+ end
+
+ it "should not store the split when Split generically disabled" do
+ @params = {'SPLIT_DISABLE' => 'true'}
+ ab_user.should_not_receive(:[]=)
+ ab_test('link_color', 'blue', 'red')
+ end
+
context "when store_override is set" do
before { Split.configuration.store_override = true }
| 18 | Merge pull request #263 from hwartig/option-to-disable-split | 0 | .rb | rb | mit | splitrb/split |
10071949 | <NME> .jscsrc
<BEF> ADDFILE
<MSG> chore(jscsrc): Added .jscsrc
<DFF> @@ -0,0 +1,75 @@
+{
+ "requireCurlyBraces": [
+ "if",
+ "else",
+ "for",
+ "while",
+ "do",
+ "try",
+ "catch"
+ ],
+ "requireSpaceAfterKeywords": [
+ "if",
+ "else",
+ "for",
+ "while",
+ "do",
+ "switch",
+ "case",
+ "return",
+ "try",
+ "catch",
+ "typeof"
+ ],
+ "requireSpaceBeforeBinaryOperators": [
+ "=", "+=", "-=", "*=", "/=", "%=", "<<=", ">>=", ">>>=",
+ "&=", "|=", "^=", "+=",
+
+ "+", "-", "*", "/", "%", "<<", ">>", ">>>", "&",
+ "|", "^", "&&", "||", "===", "==", ">=",
+ "<=", "<", ">", "!=", "!=="
+ ],
+ "requireSpaceBeforeBlockStatements": true,
+ "requireParenthesesAroundIIFE": true,
+ "requireSpacesInConditionalExpression": true,
+ "disallowSpacesInNamedFunctionExpression": {
+ "beforeOpeningRoundBrace": true
+ },
+ "disallowSpacesInFunctionDeclaration": {
+ "beforeOpeningRoundBrace": true
+ },
+ "requireBlocksOnNewline": 1,
+ "disallowEmptyBlocks": true,
+ "disallowSpacesInsideArrayBrackets": true,
+ "disallowSpacesInsideParentheses": true,
+ "disallowSpaceAfterObjectKeys": true,
+ "requireCommaBeforeLineBreak": true,
+ "disallowSpaceAfterPrefixUnaryOperators": true,
+ "disallowSpaceBeforePostfixUnaryOperators": true,
+ "disallowSpaceBeforeBinaryOperators": [
+ ","
+ ],
+ "requireSpaceBeforeBinaryOperators": true,
+ "requireSpaceAfterBinaryOperators": true,
+ "disallowKeywords": [ "with" ],
+ "disallowMultipleLineBreaks": true,
+ "validateLineBreaks": "LF",
+ "validateQuoteMarks": true,
+ "validateIndentation": 2,
+ "disallowMixedSpacesAndTabs": true,
+ "disallowTrailingWhitespace": true,
+ "disallowTrailingComma": true,
+ "disallowKeywordsOnNewLine": [ "else" ],
+ "requireLineFeedAtFileEnd": true,
+ "requireCapitalizedConstructors": true,
+ "requireDotNotation": true,
+ "disallowYodaConditions": true,
+ "requireSpacesInFunctionExpression": {
+ "beforeOpeningCurlyBrace": true
+ },
+ "disallowSpacesInFunctionExpression": {
+ "beforeOpeningRoundBrace": true
+ },
+ "disallowSpaceAfterObjectKeys": true,
+ "requireSpaceBeforeObjectValues": true
+}
\ No newline at end of file
| 75 | chore(jscsrc): Added .jscsrc | 0 | jscsrc | mit | Semantic-Org/Semantic-UI-Angular |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.