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
10072250
<NME> webpack.config.js <BEF> var path = require('path'); var webpack = require('webpack'); module.exports = { context: path.resolve('src'), devtool: "source-map", entry: { 'semantic-ui-angular': './index', 'semantic-ui-angular.min': './index' }, output: { path: path.resolve('dist'), filename: '[name].js' }, plugins: [ new webpack.optimize.UglifyJsPlugin({ include: /\.min\.js$/, minimize: true }) ], module: { loaders: [ { test: /\.ts?$/, loader: 'ts-loader' } ] }, resolve: { { test: /\.ts?$/, exclude: /node_modules/, loader: 'ts-loader' }, { test: /\.json?$/, exclude: /node_modules/, loader: 'json-loader' } ] }, tslint: { configuration: require('./tslint.json') }, resolve: { extensions: ['', '.ts', '.js'] } }; <MSG> chore(webpack): Create base webpack.config.js file <DFF> @@ -1,5 +1,14 @@ var path = require('path'); var webpack = require('webpack'); +var VERSION = require('./package.json').version; + +var banner = + '/*!\n' + + ' * Semantic-UI AngularJS integration\n' + + ' * https://github.com/semantic-org/semantic-ui-angular\n' + + ' * @license MIT\n' + + ' * v' + VERSION + '\n' + + ' */\n'; module.exports = { context: path.resolve('src'), @@ -16,11 +25,13 @@ module.exports = { new webpack.optimize.UglifyJsPlugin({ include: /\.min\.js$/, minimize: true - }) + }), + new webpack.BannerPlugin(banner, {raw: true}) ], module: { loaders: [ - { test: /\.ts?$/, loader: 'ts-loader' } + { test: /\.ts?$/, exclude: /node_modules/, loader: 'ts-loader' }, + { test: /\.json?$/, exclude: /node_modules/, loader: 'json-loader' } ] }, resolve: {
13
chore(webpack): Create base webpack.config.js file
2
.js
config
mit
Semantic-Org/Semantic-UI-Angular
10072251
<NME> utils.ts <BEF> import { EMAttribute, EMLiteral, EMNode, EMElement, EMGroup } from '@emmetio/abbreviation'; import { Container } from './walk'; /** * Walks over each child node of given markup abbreviation AST node (not including * given one) and invokes `fn` on each node. * The `fn` callback accepts context node, list of ancestor nodes and optional * state object */ export function walk<S>(node: Container, fn: WalkVisitor<S>, state?: S) { const ancestors: Container[] = [node]; const callback = (ctx: AbbreviationNode) => { fn(ctx, ancestors, state); ancestors.push(ctx); ctx.children.forEach(callback); ancestors.pop(); }; node.children.forEach(callback); } /** * Finds node which is the deepest for in current node or node itself. */ export function findDeepest(node: Container): { node: Container, parent?: Container } { let parent: Container | undefined; while (node.children.length) { parent = node; node = node.children[node.children.length - 1]; } return { parent, node }; } export function isNode(node: Container): node is AbbreviationNode { return node.type === 'AbbreviationNode'; } export function isGroup(node: EMNode): node is EMGroup { return node.type === 'EMGroup'; } <MSG> Working on content repeater <DFF> @@ -1,3 +1,4 @@ +import Scanner from '@emmetio/scanner'; import { EMAttribute, EMLiteral, EMNode, EMElement, EMGroup } from '@emmetio/abbreviation'; import { Container } from './walk'; @@ -54,3 +55,28 @@ export function isElement(node: EMNode): node is EMElement { export function isGroup(node: EMNode): node is EMGroup { return node.type === 'EMGroup'; } + +/** + * Replaces unescaped token, consumed by `token` function, with value produced + * by `value` function + */ +export function replaceToken<T>(text: string, token: (scanner: Scanner) => T, value: string | ((scanner: Scanner, arg: T) => string)): string { + const scanner = new Scanner(text); + let offset = 0; + let result = ''; + let t: T; + + while (!scanner.eof()) { + if (scanner.eat(92) /* \ */) { + scanner.pos++; + } else if (t = token(scanner)) { + result += text.slice(offset, scanner.start) + + (typeof value === 'string' ? value : value(scanner, t)); + offset = scanner.pos; + } else { + scanner.pos++; + } + } + + return result; +}
26
Working on content repeater
0
.ts
ts
mit
emmetio/emmet
10072252
<NME> utils.ts <BEF> import { EMAttribute, EMLiteral, EMNode, EMElement, EMGroup } from '@emmetio/abbreviation'; import { Container } from './walk'; /** * Walks over each child node of given markup abbreviation AST node (not including * given one) and invokes `fn` on each node. * The `fn` callback accepts context node, list of ancestor nodes and optional * state object */ export function walk<S>(node: Container, fn: WalkVisitor<S>, state?: S) { const ancestors: Container[] = [node]; const callback = (ctx: AbbreviationNode) => { fn(ctx, ancestors, state); ancestors.push(ctx); ctx.children.forEach(callback); ancestors.pop(); }; node.children.forEach(callback); } /** * Finds node which is the deepest for in current node or node itself. */ export function findDeepest(node: Container): { node: Container, parent?: Container } { let parent: Container | undefined; while (node.children.length) { parent = node; node = node.children[node.children.length - 1]; } return { parent, node }; } export function isNode(node: Container): node is AbbreviationNode { return node.type === 'AbbreviationNode'; } export function isGroup(node: EMNode): node is EMGroup { return node.type === 'EMGroup'; } <MSG> Working on content repeater <DFF> @@ -1,3 +1,4 @@ +import Scanner from '@emmetio/scanner'; import { EMAttribute, EMLiteral, EMNode, EMElement, EMGroup } from '@emmetio/abbreviation'; import { Container } from './walk'; @@ -54,3 +55,28 @@ export function isElement(node: EMNode): node is EMElement { export function isGroup(node: EMNode): node is EMGroup { return node.type === 'EMGroup'; } + +/** + * Replaces unescaped token, consumed by `token` function, with value produced + * by `value` function + */ +export function replaceToken<T>(text: string, token: (scanner: Scanner) => T, value: string | ((scanner: Scanner, arg: T) => string)): string { + const scanner = new Scanner(text); + let offset = 0; + let result = ''; + let t: T; + + while (!scanner.eof()) { + if (scanner.eat(92) /* \ */) { + scanner.pos++; + } else if (t = token(scanner)) { + result += text.slice(offset, scanner.start) + + (typeof value === 'string' ? value : value(scanner, t)); + offset = scanner.pos; + } else { + scanner.pos++; + } + } + + return result; +}
26
Working on content repeater
0
.ts
ts
mit
emmetio/emmet
10072253
<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 lambda { ab_test('xyz', '1', '2', '3') }.should_not raise_error end it "should raise the appropriate error when passed integers for alternatives" do lambda { ab_test('xyz', 1, 2, 3) }.should raise_error(ArgumentError) end 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" 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> Added spec for array as alternatives <DFF> @@ -15,6 +15,10 @@ describe Split::Helper do lambda { ab_test('xyz', '1', '2', '3') }.should_not raise_error end + it "should not raise an error when passed an array for alternatives" do + lambda { ab_test('xyz', ['1', '2', '3']) }.should_not raise_error + end + it "should raise the appropriate error when passed integers for alternatives" do lambda { ab_test('xyz', 1, 2, 3) }.should raise_error(ArgumentError) end
4
Added spec for array as alternatives
0
.rb
rb
mit
splitrb/split
10072254
<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 lambda { ab_test('xyz', '1', '2', '3') }.should_not raise_error end it "should raise the appropriate error when passed integers for alternatives" do lambda { ab_test('xyz', 1, 2, 3) }.should raise_error(ArgumentError) end 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" 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> Added spec for array as alternatives <DFF> @@ -15,6 +15,10 @@ describe Split::Helper do lambda { ab_test('xyz', '1', '2', '3') }.should_not raise_error end + it "should not raise an error when passed an array for alternatives" do + lambda { ab_test('xyz', ['1', '2', '3']) }.should_not raise_error + end + it "should raise the appropriate error when passed integers for alternatives" do lambda { ab_test('xyz', 1, 2, 3) }.should raise_error(ArgumentError) end
4
Added spec for array as alternatives
0
.rb
rb
mit
splitrb/split
10072255
<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 lambda { ab_test('xyz', '1', '2', '3') }.should_not raise_error end it "should raise the appropriate error when passed integers for alternatives" do lambda { ab_test('xyz', 1, 2, 3) }.should raise_error(ArgumentError) end 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" 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> Added spec for array as alternatives <DFF> @@ -15,6 +15,10 @@ describe Split::Helper do lambda { ab_test('xyz', '1', '2', '3') }.should_not raise_error end + it "should not raise an error when passed an array for alternatives" do + lambda { ab_test('xyz', ['1', '2', '3']) }.should_not raise_error + end + it "should raise the appropriate error when passed integers for alternatives" do lambda { ab_test('xyz', 1, 2, 3) }.should raise_error(ArgumentError) end
4
Added spec for array as alternatives
0
.rb
rb
mit
splitrb/split
10072256
<NME> divider.js <BEF> ADDFILE <MSG> feat(smDivider): Created smDivider directive <DFF> @@ -0,0 +1,39 @@ +(function() { + 'use strict'; + + angular + .module('semantic.ui.elements.divider', []) + + .directive('smDivider', smDivider); + + function smDivider() { + return { + restrict:'E', + replace: true, + transclude: true, + template: setTemplate, + link: function(scope, element, attrs, ctrl, transclude) { + + transclude(scope, function(nodes) { + element.append(nodes); + }); + } + }; + + function hasType(attrs) { + return attrs.vertical !== void 0 || attrs.horizontal !== void 0; + } + + function setTemplate(element, attrs) { + if (hasType(attrs)) { + if(attrs.vertical !== void 0) { + return '<div class="ui divider vertical"></div>'; + } else { + return '<div class="ui divider horizontal"></div>'; + } + } else { + return '<div class="ui divider"></div>'; + } + } + } +})();
39
feat(smDivider): Created smDivider directive
0
.js
js
mit
Semantic-Org/Semantic-UI-Angular
10072257
<NME> divider.js <BEF> ADDFILE <MSG> feat(smDivider): Created smDivider directive <DFF> @@ -0,0 +1,39 @@ +(function() { + 'use strict'; + + angular + .module('semantic.ui.elements.divider', []) + + .directive('smDivider', smDivider); + + function smDivider() { + return { + restrict:'E', + replace: true, + transclude: true, + template: setTemplate, + link: function(scope, element, attrs, ctrl, transclude) { + + transclude(scope, function(nodes) { + element.append(nodes); + }); + } + }; + + function hasType(attrs) { + return attrs.vertical !== void 0 || attrs.horizontal !== void 0; + } + + function setTemplate(element, attrs) { + if (hasType(attrs)) { + if(attrs.vertical !== void 0) { + return '<div class="ui divider vertical"></div>'; + } else { + return '<div class="ui divider horizontal"></div>'; + } + } else { + return '<div class="ui divider"></div>'; + } + } + } +})();
39
feat(smDivider): Created smDivider directive
0
.js
js
mit
Semantic-Org/Semantic-UI-Angular
10072258
<NME> divider.js <BEF> ADDFILE <MSG> feat(smDivider): Created smDivider directive <DFF> @@ -0,0 +1,39 @@ +(function() { + 'use strict'; + + angular + .module('semantic.ui.elements.divider', []) + + .directive('smDivider', smDivider); + + function smDivider() { + return { + restrict:'E', + replace: true, + transclude: true, + template: setTemplate, + link: function(scope, element, attrs, ctrl, transclude) { + + transclude(scope, function(nodes) { + element.append(nodes); + }); + } + }; + + function hasType(attrs) { + return attrs.vertical !== void 0 || attrs.horizontal !== void 0; + } + + function setTemplate(element, attrs) { + if (hasType(attrs)) { + if(attrs.vertical !== void 0) { + return '<div class="ui divider vertical"></div>'; + } else { + return '<div class="ui divider horizontal"></div>'; + } + } else { + return '<div class="ui divider"></div>'; + } + } + } +})();
39
feat(smDivider): Created smDivider directive
0
.js
js
mit
Semantic-Org/Semantic-UI-Angular
10072259
<NME> urls.py <BEF> ADDFILE <MSG> Move djangopypi related urls from chishop to pypi <DFF> @@ -0,0 +1,16 @@ +# -*- coding: utf-8 -*- +from django.conf.urls.defaults import patterns, url, include + +urlpatterns = patterns("", + # Simple PyPI + url(r'^/?$', "djangopypi.views.simple", + name="djangopypi-simple"), + + url(r'^(?P<dist_name>[\w\d_\-]+)/(?P<version>[\w\.\d\-_]+)/?', + "djangopypi.views.show_version", + name="djangopypi-show_version"), + + url(r'^(?P<dist_name>[\w\d_\-]+)/?', "djangopypi.views.show_links", + name="djangopypi-show_links"), +) +
16
Move djangopypi related urls from chishop to pypi
0
.py
py
bsd-3-clause
ask/chishop
10072260
<NME> README.md <BEF> Semantic-UI-Angular ################### Status: Currently migrating from https://github.com/caitp/angular-semantic [![Build Status](https://travis-ci.org/Semantic-Org/Semantic-UI-Angular.svg)](https://travis-ci.org/Semantic-Org/Semantic-UI-Angular) [![Dependency Status](https://david-dm.org/Semantic-Org/Semantic-UI-Angular.svg)](https://david-dm.org/Semantic-Org/Semantic-UI-Angular) [![devDependency Status](https://david-dm.org/Semantic-Org/Semantic-UI-Angular/dev-status.svg)](https://david-dm.org/Semantic-Org/Semantic-UI-Angular#info=devDependencies) [![Commitizen friendly](https://img.shields.io/badge/commitizen-friendly-brightgreen.svg)](http://commitizen.github.io/cz-cli/) **Semantic-UI-Angular** is a pure AngularJS 1.x set of directives for Semantic-UI components. We are considering Angular 2 support in the future. We've decided to use TypeScript as a step to Angular 2 friendly environment. Status ------ **Work in progress** We are working on setting up proper environment, contribution guidelines and everything else for comfortable community contributions. Once we release first `alpha.0` we are happy to get community help. Support ------- We support AngularJS 1.4.8 version. Building Semantic-UI-Angular ---------------------------- You have to have `nodejs` installed before running following commands. ``` npm install npm run build ``` The distribution packages will be stored in `dist` folder. Running tests ------------- Single run: ``` npm test ``` Dev mode: ``` npm run test-dev ``` <MSG> docs(README.md): make it a heading! <DFF> @@ -1,4 +1,4 @@ Semantic-UI-Angular -################### +=================== Status: Currently migrating from https://github.com/caitp/angular-semantic
1
docs(README.md): make it a heading!
1
.md
md
mit
Semantic-Org/Semantic-UI-Angular
10072261
<NME> README.md <BEF> Semantic-UI-Angular ################### Status: Currently migrating from https://github.com/caitp/angular-semantic [![Build Status](https://travis-ci.org/Semantic-Org/Semantic-UI-Angular.svg)](https://travis-ci.org/Semantic-Org/Semantic-UI-Angular) [![Dependency Status](https://david-dm.org/Semantic-Org/Semantic-UI-Angular.svg)](https://david-dm.org/Semantic-Org/Semantic-UI-Angular) [![devDependency Status](https://david-dm.org/Semantic-Org/Semantic-UI-Angular/dev-status.svg)](https://david-dm.org/Semantic-Org/Semantic-UI-Angular#info=devDependencies) [![Commitizen friendly](https://img.shields.io/badge/commitizen-friendly-brightgreen.svg)](http://commitizen.github.io/cz-cli/) **Semantic-UI-Angular** is a pure AngularJS 1.x set of directives for Semantic-UI components. We are considering Angular 2 support in the future. We've decided to use TypeScript as a step to Angular 2 friendly environment. Status ------ **Work in progress** We are working on setting up proper environment, contribution guidelines and everything else for comfortable community contributions. Once we release first `alpha.0` we are happy to get community help. Support ------- We support AngularJS 1.4.8 version. Building Semantic-UI-Angular ---------------------------- You have to have `nodejs` installed before running following commands. ``` npm install npm run build ``` The distribution packages will be stored in `dist` folder. Running tests ------------- Single run: ``` npm test ``` Dev mode: ``` npm run test-dev ``` <MSG> docs(README.md): make it a heading! <DFF> @@ -1,4 +1,4 @@ Semantic-UI-Angular -################### +=================== Status: Currently migrating from https://github.com/caitp/angular-semantic
1
docs(README.md): make it a heading!
1
.md
md
mit
Semantic-Org/Semantic-UI-Angular
10072262
<NME> README.md <BEF> Semantic-UI-Angular ################### Status: Currently migrating from https://github.com/caitp/angular-semantic [![Build Status](https://travis-ci.org/Semantic-Org/Semantic-UI-Angular.svg)](https://travis-ci.org/Semantic-Org/Semantic-UI-Angular) [![Dependency Status](https://david-dm.org/Semantic-Org/Semantic-UI-Angular.svg)](https://david-dm.org/Semantic-Org/Semantic-UI-Angular) [![devDependency Status](https://david-dm.org/Semantic-Org/Semantic-UI-Angular/dev-status.svg)](https://david-dm.org/Semantic-Org/Semantic-UI-Angular#info=devDependencies) [![Commitizen friendly](https://img.shields.io/badge/commitizen-friendly-brightgreen.svg)](http://commitizen.github.io/cz-cli/) **Semantic-UI-Angular** is a pure AngularJS 1.x set of directives for Semantic-UI components. We are considering Angular 2 support in the future. We've decided to use TypeScript as a step to Angular 2 friendly environment. Status ------ **Work in progress** We are working on setting up proper environment, contribution guidelines and everything else for comfortable community contributions. Once we release first `alpha.0` we are happy to get community help. Support ------- We support AngularJS 1.4.8 version. Building Semantic-UI-Angular ---------------------------- You have to have `nodejs` installed before running following commands. ``` npm install npm run build ``` The distribution packages will be stored in `dist` folder. Running tests ------------- Single run: ``` npm test ``` Dev mode: ``` npm run test-dev ``` <MSG> docs(README.md): make it a heading! <DFF> @@ -1,4 +1,4 @@ Semantic-UI-Angular -################### +=================== Status: Currently migrating from https://github.com/caitp/angular-semantic
1
docs(README.md): make it a heading!
1
.md
md
mit
Semantic-Org/Semantic-UI-Angular
10072263
<NME> README.md <BEF> # [Split](https://libraries.io/rubygems/split) [![Gem Version](https://badge.fury.io/rb/split.svg)](http://badge.fury.io/rb/split) ![Build status](https://github.com/splitrb/split/actions/workflows/ci.yml/badge.svg?branch=main) [![Code Climate](https://codeclimate.com/github/splitrb/split/badges/gpa.svg)](https://codeclimate.com/github/splitrb/split) [![Test Coverage](https://codeclimate.com/github/splitrb/split/badges/coverage.svg)](https://codeclimate.com/github/splitrb/split/coverage) [![standard-readme compliant](https://img.shields.io/badge/readme%20style-standard-brightgreen.svg?style=flat-square)](https://github.com/RichardLitt/standard-readme) [![Open Source Helpers](https://www.codetriage.com/splitrb/split/badges/users.svg)](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") # 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| alternatives_by_experiment.fetch(experiment) { |key| raise "Unknown experiment '#{key}'" } end end 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 ![split_screenshot](https://raw.githubusercontent.com/caser/caser.github.io/master/dashboard.png) ## 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> Update RSpec helper to support block syntax Adds support for the helpers block form `ab_test(:experiment) { |variant| ... }`, based on the example from RSpecs docs[1]. [1]: https://relishapp.com/rspec/rspec-mocks/v/3-2/docs/configuring-responses/block-implementation#yield-to-the-caller's-block <DFF> @@ -175,8 +175,10 @@ module SplitHelper # 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| - alternatives_by_experiment.fetch(experiment) { |key| raise "Unknown experiment '#{key}'" } + 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
4
Update RSpec helper to support block syntax
2
.md
md
mit
splitrb/split
10072264
<NME> README.md <BEF> # [Split](https://libraries.io/rubygems/split) [![Gem Version](https://badge.fury.io/rb/split.svg)](http://badge.fury.io/rb/split) ![Build status](https://github.com/splitrb/split/actions/workflows/ci.yml/badge.svg?branch=main) [![Code Climate](https://codeclimate.com/github/splitrb/split/badges/gpa.svg)](https://codeclimate.com/github/splitrb/split) [![Test Coverage](https://codeclimate.com/github/splitrb/split/badges/coverage.svg)](https://codeclimate.com/github/splitrb/split/coverage) [![standard-readme compliant](https://img.shields.io/badge/readme%20style-standard-brightgreen.svg?style=flat-square)](https://github.com/RichardLitt/standard-readme) [![Open Source Helpers](https://www.codetriage.com/splitrb/split/badges/users.svg)](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") # 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| alternatives_by_experiment.fetch(experiment) { |key| raise "Unknown experiment '#{key}'" } end end 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 ![split_screenshot](https://raw.githubusercontent.com/caser/caser.github.io/master/dashboard.png) ## 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> Update RSpec helper to support block syntax Adds support for the helpers block form `ab_test(:experiment) { |variant| ... }`, based on the example from RSpecs docs[1]. [1]: https://relishapp.com/rspec/rspec-mocks/v/3-2/docs/configuring-responses/block-implementation#yield-to-the-caller's-block <DFF> @@ -175,8 +175,10 @@ module SplitHelper # 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| - alternatives_by_experiment.fetch(experiment) { |key| raise "Unknown experiment '#{key}'" } + 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
4
Update RSpec helper to support block syntax
2
.md
md
mit
splitrb/split
10072265
<NME> README.md <BEF> # [Split](https://libraries.io/rubygems/split) [![Gem Version](https://badge.fury.io/rb/split.svg)](http://badge.fury.io/rb/split) ![Build status](https://github.com/splitrb/split/actions/workflows/ci.yml/badge.svg?branch=main) [![Code Climate](https://codeclimate.com/github/splitrb/split/badges/gpa.svg)](https://codeclimate.com/github/splitrb/split) [![Test Coverage](https://codeclimate.com/github/splitrb/split/badges/coverage.svg)](https://codeclimate.com/github/splitrb/split/coverage) [![standard-readme compliant](https://img.shields.io/badge/readme%20style-standard-brightgreen.svg?style=flat-square)](https://github.com/RichardLitt/standard-readme) [![Open Source Helpers](https://www.codetriage.com/splitrb/split/badges/users.svg)](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") # 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| alternatives_by_experiment.fetch(experiment) { |key| raise "Unknown experiment '#{key}'" } end end 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 ![split_screenshot](https://raw.githubusercontent.com/caser/caser.github.io/master/dashboard.png) ## 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> Update RSpec helper to support block syntax Adds support for the helpers block form `ab_test(:experiment) { |variant| ... }`, based on the example from RSpecs docs[1]. [1]: https://relishapp.com/rspec/rspec-mocks/v/3-2/docs/configuring-responses/block-implementation#yield-to-the-caller's-block <DFF> @@ -175,8 +175,10 @@ module SplitHelper # 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| - alternatives_by_experiment.fetch(experiment) { |key| raise "Unknown experiment '#{key}'" } + 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
4
Update RSpec helper to support block syntax
2
.md
md
mit
splitrb/split
10072266
<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.homepage = "https://github.com/andrew/split" s.summary = %q{Rack based split testing framework} s.rubyforge_project = "split" s.files = `git ls-files`.split("\n") "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", "~> 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> Add required_ruby_version to gemspec <DFF> @@ -12,6 +12,8 @@ Gem::Specification.new do |s| s.homepage = "https://github.com/andrew/split" s.summary = %q{Rack based split testing framework} + s.required_ruby_version = '>= 1.9.2' + s.rubyforge_project = "split" s.files = `git ls-files`.split("\n")
2
Add required_ruby_version to gemspec
0
.gemspec
gemspec
mit
splitrb/split
10072267
<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.homepage = "https://github.com/andrew/split" s.summary = %q{Rack based split testing framework} s.rubyforge_project = "split" s.files = `git ls-files`.split("\n") "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", "~> 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> Add required_ruby_version to gemspec <DFF> @@ -12,6 +12,8 @@ Gem::Specification.new do |s| s.homepage = "https://github.com/andrew/split" s.summary = %q{Rack based split testing framework} + s.required_ruby_version = '>= 1.9.2' + s.rubyforge_project = "split" s.files = `git ls-files`.split("\n")
2
Add required_ruby_version to gemspec
0
.gemspec
gemspec
mit
splitrb/split
10072268
<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.homepage = "https://github.com/andrew/split" s.summary = %q{Rack based split testing framework} s.rubyforge_project = "split" s.files = `git ls-files`.split("\n") "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", "~> 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> Add required_ruby_version to gemspec <DFF> @@ -12,6 +12,8 @@ Gem::Specification.new do |s| s.homepage = "https://github.com/andrew/split" s.summary = %q{Rack based split testing framework} + s.required_ruby_version = '>= 1.9.2' + s.rubyforge_project = "split" s.files = `git ls-files`.split("\n")
2
Add required_ruby_version to gemspec
0
.gemspec
gemspec
mit
splitrb/split
10072269
<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 = ["andrewnez@gmail.com"] 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_development_dependency 'bundler', '~> 1.0' s.add_development_dependency 'rspec', '~> 2.6' s.add_development_dependency 'rack-test', '~> 0.6' s.add_development_dependency 'guard-rspec', '~> 0.4' end 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> Updated guard-rpesc to 1.2 <DFF> @@ -26,5 +26,5 @@ Gem::Specification.new do |s| s.add_development_dependency 'bundler', '~> 1.0' s.add_development_dependency 'rspec', '~> 2.6' s.add_development_dependency 'rack-test', '~> 0.6' - s.add_development_dependency 'guard-rspec', '~> 0.4' + s.add_development_dependency 'guard-rspec', '~> 1.2' end
1
Updated guard-rpesc to 1.2
1
.gemspec
gemspec
mit
splitrb/split
10072270
<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 = ["andrewnez@gmail.com"] 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_development_dependency 'bundler', '~> 1.0' s.add_development_dependency 'rspec', '~> 2.6' s.add_development_dependency 'rack-test', '~> 0.6' s.add_development_dependency 'guard-rspec', '~> 0.4' end 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> Updated guard-rpesc to 1.2 <DFF> @@ -26,5 +26,5 @@ Gem::Specification.new do |s| s.add_development_dependency 'bundler', '~> 1.0' s.add_development_dependency 'rspec', '~> 2.6' s.add_development_dependency 'rack-test', '~> 0.6' - s.add_development_dependency 'guard-rspec', '~> 0.4' + s.add_development_dependency 'guard-rspec', '~> 1.2' end
1
Updated guard-rpesc to 1.2
1
.gemspec
gemspec
mit
splitrb/split
10072271
<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 = ["andrewnez@gmail.com"] 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_development_dependency 'bundler', '~> 1.0' s.add_development_dependency 'rspec', '~> 2.6' s.add_development_dependency 'rack-test', '~> 0.6' s.add_development_dependency 'guard-rspec', '~> 0.4' end 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> Updated guard-rpesc to 1.2 <DFF> @@ -26,5 +26,5 @@ Gem::Specification.new do |s| s.add_development_dependency 'bundler', '~> 1.0' s.add_development_dependency 'rspec', '~> 2.6' s.add_development_dependency 'rack-test', '~> 0.6' - s.add_development_dependency 'guard-rspec', '~> 0.4' + s.add_development_dependency 'guard-rspec', '~> 1.2' end
1
Updated guard-rpesc to 1.2
1
.gemspec
gemspec
mit
splitrb/split
10072272
<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 attr_accessor :on_before_experiment_delete attr_accessor :include_rails_helper attr_accessor :beta_probability_simulations attr_accessor :winning_alternative_recalculation_interval attr_accessor :redis attr_accessor :dashboard_pagination_default_per_page attr_accessor :cache attr_reader :experiments attr_writer :bots attr_writer :robot_regex 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", "bot@linkfluence.net" => "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| end def initialize @robot_regex = /\b(#{BOTS.keys.join('|')})\b|^\W*$/i @ignore_ip_addresses = [] @db_failover = false @db_failover_on_db_error = proc{|error|} # e.g. use Rails logger here 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 hash[key.to_s] || hash[key.to_sym] end end end end 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> Merge pull request #132 from dimko/patch-3 Fixed robot regexp escaping <DFF> @@ -138,7 +138,7 @@ module Split end def initialize - @robot_regex = /\b(#{BOTS.keys.join('|')})\b|^\W*$/i + @robot_regex = /\b(?:#{escaped_bots.join('|')})\b|\A\W*\z/i @ignore_ip_addresses = [] @db_failover = false @db_failover_on_db_error = proc{|error|} # e.g. use Rails logger here @@ -157,5 +157,9 @@ module Split hash[key.to_s] || hash[key.to_sym] end end + + def escaped_bots + BOTS.map { |key, _| Regexp.escape(key) } + end end end
5
Merge pull request #132 from dimko/patch-3
1
.rb
rb
mit
splitrb/split
10072273
<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 attr_accessor :on_before_experiment_delete attr_accessor :include_rails_helper attr_accessor :beta_probability_simulations attr_accessor :winning_alternative_recalculation_interval attr_accessor :redis attr_accessor :dashboard_pagination_default_per_page attr_accessor :cache attr_reader :experiments attr_writer :bots attr_writer :robot_regex 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", "bot@linkfluence.net" => "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| end def initialize @robot_regex = /\b(#{BOTS.keys.join('|')})\b|^\W*$/i @ignore_ip_addresses = [] @db_failover = false @db_failover_on_db_error = proc{|error|} # e.g. use Rails logger here 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 hash[key.to_s] || hash[key.to_sym] end end end end 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> Merge pull request #132 from dimko/patch-3 Fixed robot regexp escaping <DFF> @@ -138,7 +138,7 @@ module Split end def initialize - @robot_regex = /\b(#{BOTS.keys.join('|')})\b|^\W*$/i + @robot_regex = /\b(?:#{escaped_bots.join('|')})\b|\A\W*\z/i @ignore_ip_addresses = [] @db_failover = false @db_failover_on_db_error = proc{|error|} # e.g. use Rails logger here @@ -157,5 +157,9 @@ module Split hash[key.to_s] || hash[key.to_sym] end end + + def escaped_bots + BOTS.map { |key, _| Regexp.escape(key) } + end end end
5
Merge pull request #132 from dimko/patch-3
1
.rb
rb
mit
splitrb/split
10072274
<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 attr_accessor :on_before_experiment_delete attr_accessor :include_rails_helper attr_accessor :beta_probability_simulations attr_accessor :winning_alternative_recalculation_interval attr_accessor :redis attr_accessor :dashboard_pagination_default_per_page attr_accessor :cache attr_reader :experiments attr_writer :bots attr_writer :robot_regex 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", "bot@linkfluence.net" => "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| end def initialize @robot_regex = /\b(#{BOTS.keys.join('|')})\b|^\W*$/i @ignore_ip_addresses = [] @db_failover = false @db_failover_on_db_error = proc{|error|} # e.g. use Rails logger here 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 hash[key.to_s] || hash[key.to_sym] end end end end 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> Merge pull request #132 from dimko/patch-3 Fixed robot regexp escaping <DFF> @@ -138,7 +138,7 @@ module Split end def initialize - @robot_regex = /\b(#{BOTS.keys.join('|')})\b|^\W*$/i + @robot_regex = /\b(?:#{escaped_bots.join('|')})\b|\A\W*\z/i @ignore_ip_addresses = [] @db_failover = false @db_failover_on_db_error = proc{|error|} # e.g. use Rails logger here @@ -157,5 +157,9 @@ module Split hash[key.to_s] || hash[key.to_sym] end end + + def escaped_bots + BOTS.map { |key, _| Regexp.escape(key) } + end end end
5
Merge pull request #132 from dimko/patch-3
1
.rb
rb
mit
splitrb/split
10072275
<NME> tokenizer.ts <BEF> import { deepEqual } from 'assert'; import tokenize from '../src/tokenizer'; describe('Tokenizer', () => { it('numeric values', () => { deepEqual(tokenize('p10'), [ { type: 'Literal', value: 'p', start: 0, end: 1 }, { type: 'NumberValue', value: 10, unit: '', start: 1, end: 3 } ]); deepEqual(tokenize('p-10'), [ { type: 'Literal', value: 'p', start: 0, end: 1 }, { type: 'NumberValue', value: -10, unit: '', start: 1, end: 4 } ]); deepEqual(tokenize('p-10-'), [ { type: 'Literal', value: 'p', start: 0, end: 1 }, { type: 'NumberValue', value: -10, unit: '', start: 1, end: 4 }, { type: 'Operator', operator: '-', start: 4, end: 5 } ]); deepEqual(tokenize('p-10-20'), [ { type: 'Literal', value: 'p', start: 0, end: 1 }, { type: 'NumberValue', value: -10, unit: '', start: 1, end: 4 }, { type: 'Operator', operator: '-', start: 4, end: 5 }, { type: 'NumberValue', value: 20, unit: '', start: 5, end: 7 } ]); deepEqual(tokenize('p-10--20'), [ { type: 'Literal', value: 'p', start: 0, end: 1 }, { type: 'NumberValue', value: -10, unit: '', start: 1, end: 4 }, { type: 'Operator', operator: '-', start: 4, end: 5 }, { type: 'NumberValue', value: -20, unit: '', start: 5, end: 8 } ]); deepEqual(tokenize('p-10-20--30'), [ { type: 'Literal', value: 'p', start: 0, end: 1 }, { type: 'NumberValue', value: -10, unit: '', start: 1, end: 4 }, { type: 'Operator', operator: '-', start: 4, end: 5 }, { type: 'NumberValue', value: 20, unit: '', start: 5, end: 7 }, { type: 'Operator', operator: '-', start: 7, end: 8 }, { type: 'NumberValue', value: -30, unit: '', start: 8, end: 11 } ]); deepEqual(tokenize('p-10p-20--30'), [ { type: 'Literal', value: 'p', start: 0, end: 1 }, { type: 'NumberValue', value: -10, unit: 'p', start: 1, end: 5 }, { type: 'NumberValue', value: -20, unit: '', start: 5, end: 8 }, { type: 'Operator', operator: '-', start: 8, end: 9 }, { type: 'NumberValue', value: -30, unit: '', start: 9, end: 12 } ]); deepEqual(tokenize('p-10%-20--30'), [ { type: 'Literal', value: 'p', start: 0, end: 1 }, { type: 'NumberValue', value: -10, unit: '%', start: 1, end: 5 }, { type: 'NumberValue', value: -20, unit: '', start: 5, end: 8 }, { type: 'Operator', operator: '-', start: 8, end: 9 }, { type: 'NumberValue', value: -30, unit: '', start: 9, end: 12 } ]); }); it('float values', () => { deepEqual(tokenize('p.5'), [ { type: 'Literal', value: 'p', start: 0, end: 1 }, { type: 'NumberValue', value: 0.5, unit: '', start: 1, end: 3 } ]); deepEqual(tokenize('p-.5'), [ { type: 'Literal', value: 'p', start: 0, end: 1 }, { type: 'NumberValue', value: -0.5, unit: '', start: 1, end: 4 } ]); deepEqual(tokenize('p.1.2.3'), [ { type: 'Literal', value: 'p', start: 0, end: 1 }, { type: 'NumberValue', value: 0.1, unit: '', start: 1, end: 3 }, { type: 'NumberValue', value: 0.2, unit: '', start: 3, end: 5 }, { type: 'NumberValue', value: 0.3, unit: '', start: 5, end: 7 } ]); deepEqual(tokenize('p.1-.2.3'), [ { type: 'Literal', value: 'p', start: 0, end: 1 }, { type: 'NumberValue', value: 0.1, unit: '', start: 1, end: 3 }, { type: 'Operator', operator: '-', start: 3, end: 4 }, { type: 'NumberValue', value: 0.2, unit: '', start: 4, end: 6 }, { type: 'NumberValue', value: 0.3, unit: '', start: 6, end: 8 } ]); deepEqual(tokenize('p.1--.2.3'), [ { type: 'Literal', value: 'p', start: 0, end: 1 }, { type: 'NumberValue', value: 0.1, unit: '', start: 1, end: 3 }, { type: 'Operator', operator: '-', start: 3, end: 4 }, { type: 'NumberValue', value: -0.2, unit: '', start: 4, end: 7 }, { type: 'NumberValue', value: 0.3, unit: '', start: 7, end: 9 } ]); deepEqual(tokenize('10'), [ { type: 'NumberValue', value: 10, unit: '', start: 0, end: 2 }, ]); deepEqual(tokenize('.1'), [ { type: 'NumberValue', value: 0.1, unit: '', start: 0, end: 2 }, ]); throws(() => tokenize('.foo'), /Unexpected character at 1/); // throws(() => tokenize('.foo'), /Unexpected character at 1/); }); it('color values', () => { deepEqual(tokenize('c#'), [ { type: 'Literal', value: 'c', start: 0, end: 1 }, { type: 'ColorValue', r: 0, g: 0, b: 0, a: 1, raw: '', start: 1, end: 2 } ]); deepEqual(tokenize('c#1'), [ { type: 'Literal', value: 'c', start: 0, end: 1 }, { type: 'ColorValue', r: 17, g: 17, b: 17, a: 1, raw: '1', start: 1, end: 3 } ]); deepEqual(tokenize('c#.'), [ { type: 'Literal', value: 'c', start: 0, end: 1 }, { type: 'ColorValue', r: 0, g: 0, b: 0, a: 1, raw: '.', start: 1, end: 3 } ]); deepEqual(tokenize('c#f'), [ { type: 'Literal', value: 'c', start: 0, end: 1 }, { type: 'ColorValue', r: 255, g: 255, b: 255, a: 1, raw: 'f', start: 1, end: 3 } ]); deepEqual(tokenize('c#a#b#c'), [ { type: 'Literal', value: 'c', start: 0, end: 1 }, { type: 'ColorValue', r: 170, g: 170, b: 170, a: 1, raw: 'a', start: 1, end: 3 }, { type: 'ColorValue', r: 187, g: 187, b: 187, a: 1, raw: 'b', start: 3, end: 5 }, { type: 'ColorValue', r: 204, g: 204, b: 204, a: 1, raw: 'c', start: 5, end: 7 } ]); deepEqual(tokenize('c#af'), [ { type: 'Literal', value: 'c', start: 0, end: 1 }, { type: 'ColorValue', r: 175, g: 175, b: 175, a: 1, raw: 'af', start: 1, end: 4 } ]); deepEqual(tokenize('c#fc0'), [ { type: 'Literal', value: 'c', start: 0, end: 1 }, { type: 'ColorValue', r: 255, g: 204, b: 0, a: 1, raw: 'fc0', start: 1, end: 5 } ]); deepEqual(tokenize('c#11.5'), [ { type: 'Literal', value: 'c', start: 0, end: 1 }, { type: 'ColorValue', r: 17, g: 17, b: 17, a: 0.5, raw: '11.5', start: 1, end: 6 } ]); deepEqual(tokenize('c#.99'), [ { type: 'Literal', value: 'c', start: 0, end: 1 }, { type: 'ColorValue', r: 0, g: 0, b: 0, a: 0.99, raw: '.99', start: 1, end: 5 } ]); deepEqual(tokenize('c#t'), [ { type: 'Literal', value: 'c', start: 0, end: 1 }, { type: 'ColorValue', r: 0, g: 0, b: 0, a: 0, raw: 't', start: 1, end: 3 } ]); deepEqual(tokenize('c#${fff}'), [ { type: 'Literal', value: 'c', start: 0, end: 1 }, { type: 'Literal', value: '#', start: 1, end: 2 }, { type: 'Field', index: undefined, name: 'fff', start: 2, end: 8 } ]); }); it('keywords', () => { deepEqual(tokenize('m:a'), [ { type: 'Literal', value: 'm', start: 0, end: 1 }, { type: 'Operator', operator: ':', start: 1, end: 2 }, { type: 'Literal', value: 'a', start: 2, end: 3 } ]); deepEqual(tokenize('m-a'), [ { type: 'Literal', value: 'm', start: 0, end: 1 }, { type: 'Operator', operator: '-', start: 1, end: 2 }, { type: 'Literal', value: 'a', start: 2, end: 3 }, { type: 'NumberValue', value: 0, unit: '', start: 3, end: 4 } ]); deepEqual(tokenize('m-a0-a'), [ { type: 'Literal', value: 'm', start: 0, end: 1 }, { type: 'Operator', operator: '-', start: 1, end: 2 }, { type: 'Literal', value: 'a', start: 2, end: 3 }, { type: 'NumberValue', value: 0, unit: '', start: 3, end: 4 }, { type: 'Operator', operator: '-', start: 4, end: 5 }, { type: 'Literal', value: 'a', start: 5, end: 6 } ]); { type: 'Literal', value: 'a', start: 2, end: 3 }, { type: 'NumberValue', value: 0, rawValue: '0', unit: '', start: 3, end: 4 } ]); deepEqual(tokenize('m-a0-a'), [ { type: 'Literal', value: 'm', start: 0, end: 1 }, { type: 'Operator', operator: '-', start: 1, end: 2 }, { type: 'Literal', value: 'a', start: 2, end: 3 }, { type: 'NumberValue', value: 0, rawValue: '0', unit: '', start: 3, end: 4 }, { type: 'Operator', operator: '-', start: 4, end: 5 }, { type: 'Literal', value: 'a', start: 5, end: 6 } { type: 'WhiteSpace', start: 21, end: 22 }, { type: 'Literal', value: 'rgb', start: 22, end: 25 }, { type: 'Bracket', open: true, start: 25, end: 26 }, { type: 'NumberValue', value: 0, unit: '', start: 26, end: 27 }, { type: 'Operator', operator: ',', start: 27, end: 28 }, { type: 'WhiteSpace', start: 28, end: 29 }, { type: 'NumberValue', value: 0, unit: '', start: 29, end: 30 }, { type: 'Operator', operator: ',', start: 30, end: 31 }, { type: 'WhiteSpace', start: 31, end: 32 }, { type: 'NumberValue', value: 0, unit: '', start: 32, end: 33 }, { type: 'Bracket', open: false, start: 33, end: 34 }, { type: 'WhiteSpace', start: 34, end: 35 }, { type: 'NumberValue', value: 10, unit: '%', start: 35, end: 38 }, { type: 'Bracket', open: false, start: 38, end: 39 } ]); }); { type: 'Operator', operator: ',', start: 27, end: 28 }, { type: 'WhiteSpace', start: 28, end: 29 }, { type: 'NumberValue', value: 0, rawValue: '0', unit: '', start: 29, end: 30 }, { type: 'Operator', operator: ',', start: 30, end: 31 }, { type: 'WhiteSpace', start: 31, end: 32 }, { type: 'NumberValue', value: 0, rawValue: '0', unit: '', start: 32, end: 33 }, { type: 'Bracket', open: false, start: 33, end: 34 }, { type: 'WhiteSpace', start: 34, end: 35 }, { type: 'NumberValue', value: 10, rawValue: '10', unit: '%', start: 35, end: 38 }, { type: 'Bracket', open: false, start: 38, end: 39 } deepEqual(tokenize('p10!'), [ { type: 'Literal', value: 'p', start: 0, end: 1 }, { type: 'NumberValue', value: 10, unit: '', start: 1, end: 3 }, { type: 'Operator', operator: '!', start: 3, end: 4 } ]); }); it('mixed', () => { deepEqual(tokenize('bd1-s#fc0'), [ { type: 'Literal', value: 'bd', start: 0, end: 2 }, { type: 'NumberValue', value: 1, unit: '', start: 2, end: 3 }, { type: 'Operator', operator: '-', start: 3, end: 4 }, { type: 'Literal', value: 's', start: 4, end: 5 }, { type: 'ColorValue', r: 255, g: 204, b: 0, a: 1, raw: 'fc0', start: 5, end: 9 } { type: 'NumberValue', value: 10, rawValue: '10', unit: '', start: 1, end: 3 }, { type: 'Operator', operator: '!', start: 3, end: 4 } ]); { type: 'Literal', value: 'bd', start: 0, end: 2 }, { type: 'ColorValue', r: 255, g: 204, b: 0, a: 1, raw: 'fc0', start: 2, end: 6 }, { type: 'Operator', operator: '-', start: 6, end: 7 }, { type: 'NumberValue', value: 1, unit: '', start: 7, end: 8 } ]); deepEqual(tokenize('p0+m0'), [ { type: 'Literal', value: 'p', start: 0, end: 1 }, { type: 'NumberValue', value: 0, unit: '', start: 1, end: 2 }, { type: 'Operator', operator: '+', start: 2, end: 3 }, { type: 'Literal', value: 'm', start: 3, end: 4 }, { type: 'NumberValue', value: 0, unit: '', start: 4, end: 5 } ]); deepEqual(tokenize('p0!+m0!'), [ { type: 'Literal', value: 'p', start: 0, end: 1 }, { type: 'NumberValue', value: 0, unit: '', start: 1, end: 2 }, { type: 'Operator', operator: '!', start: 2, end: 3 }, { type: 'Operator', operator: '+', start: 3, end: 4 }, { type: 'Literal', value: 'm', start: 4, end: 5 }, { type: 'NumberValue', value: 0, unit: '', start: 5, end: 6 }, { type: 'Operator', operator: '!', start: 6, end: 7 } ]); ]); deepEqual(tokenize('p0!+m0!'), [ { type: 'Literal', value: 'p', start: 0, end: 1 }, { type: 'NumberValue', value: 0, rawValue: '0', unit: '', start: 1, end: 2 }, { type: 'Operator', operator: '!', start: 2, end: 3 }, { type: 'Operator', operator: '+', start: 3, end: 4 }, { type: 'Literal', value: 'm', start: 4, end: 5 }, { type: 'NumberValue', value: 0, rawValue: '0', unit: '', start: 5, end: 6 }, { type: 'Operator', operator: '!', start: 6, end: 7 } ]); deepEqual(tokenize('${2:0}%'), [ { type: 'Field', index: 2, name: '0', start: 0, end: 6 }, { type: 'Literal', value: '%', start: 6, end: 7 } ]); deepEqual(tokenize('.${1:5}'), [ { type: 'Literal', value: '.', start: 0, end: 1 }, { type: 'Field', index: 1, name: '5', start: 1, end: 7 }, ]); }); deepEqual(tokenize('@k10'), [ { type: 'Literal', value: '@k', start: 0, end: 2 }, { type: 'NumberValue', value: 10, unit: '', start: 2, end: 4 } ]); }); }); deepEqual(tokenize('foo$bar-2'), [ { type: 'Literal', value: 'foo', start: 0, end: 3 }, { type: 'Literal', value: '$bar-2', start: 3, end: 9 } ]); deepEqual(tokenize('foo$bar@bam'), [ { type: 'Literal', value: 'foo', start: 0, end: 3 }, { type: 'Literal', value: '$bar', start: 3, end: 7 }, { type: 'Literal', value: '@bam', start: 7, end: 11 } ]); deepEqual(tokenize('@k10'), [ { type: 'Literal', value: '@k', start: 0, end: 2 }, { type: 'NumberValue', value: 10, rawValue: '10', unit: '', start: 2, end: 4 } ]); }); }); <MSG> Support trailing dots in CSS abbreviations <DFF> @@ -5,100 +5,100 @@ describe('Tokenizer', () => { it('numeric values', () => { deepEqual(tokenize('p10'), [ { type: 'Literal', value: 'p', start: 0, end: 1 }, - { type: 'NumberValue', value: 10, unit: '', start: 1, end: 3 } + { type: 'NumberValue', value: 10, rawValue: '10', unit: '', start: 1, end: 3 } ]); deepEqual(tokenize('p-10'), [ { type: 'Literal', value: 'p', start: 0, end: 1 }, - { type: 'NumberValue', value: -10, unit: '', start: 1, end: 4 } + { type: 'NumberValue', value: -10, rawValue: '-10', unit: '', start: 1, end: 4 } ]); deepEqual(tokenize('p-10-'), [ { type: 'Literal', value: 'p', start: 0, end: 1 }, - { type: 'NumberValue', value: -10, unit: '', start: 1, end: 4 }, + { type: 'NumberValue', value: -10, rawValue: '-10', unit: '', start: 1, end: 4 }, { type: 'Operator', operator: '-', start: 4, end: 5 } ]); deepEqual(tokenize('p-10-20'), [ { type: 'Literal', value: 'p', start: 0, end: 1 }, - { type: 'NumberValue', value: -10, unit: '', start: 1, end: 4 }, + { type: 'NumberValue', value: -10, rawValue: '-10', unit: '', start: 1, end: 4 }, { type: 'Operator', operator: '-', start: 4, end: 5 }, - { type: 'NumberValue', value: 20, unit: '', start: 5, end: 7 } + { type: 'NumberValue', value: 20, rawValue: '20', unit: '', start: 5, end: 7 } ]); deepEqual(tokenize('p-10--20'), [ { type: 'Literal', value: 'p', start: 0, end: 1 }, - { type: 'NumberValue', value: -10, unit: '', start: 1, end: 4 }, + { type: 'NumberValue', value: -10, rawValue: '-10', unit: '', start: 1, end: 4 }, { type: 'Operator', operator: '-', start: 4, end: 5 }, - { type: 'NumberValue', value: -20, unit: '', start: 5, end: 8 } + { type: 'NumberValue', value: -20, rawValue: '-20', unit: '', start: 5, end: 8 } ]); deepEqual(tokenize('p-10-20--30'), [ { type: 'Literal', value: 'p', start: 0, end: 1 }, - { type: 'NumberValue', value: -10, unit: '', start: 1, end: 4 }, + { type: 'NumberValue', value: -10, rawValue: '-10', unit: '', start: 1, end: 4 }, { type: 'Operator', operator: '-', start: 4, end: 5 }, - { type: 'NumberValue', value: 20, unit: '', start: 5, end: 7 }, + { type: 'NumberValue', value: 20, rawValue: '20', unit: '', start: 5, end: 7 }, { type: 'Operator', operator: '-', start: 7, end: 8 }, - { type: 'NumberValue', value: -30, unit: '', start: 8, end: 11 } + { type: 'NumberValue', value: -30, rawValue: '-30', unit: '', start: 8, end: 11 } ]); deepEqual(tokenize('p-10p-20--30'), [ { type: 'Literal', value: 'p', start: 0, end: 1 }, - { type: 'NumberValue', value: -10, unit: 'p', start: 1, end: 5 }, - { type: 'NumberValue', value: -20, unit: '', start: 5, end: 8 }, + { type: 'NumberValue', value: -10, rawValue: '-10', unit: 'p', start: 1, end: 5 }, + { type: 'NumberValue', value: -20, rawValue: '-20', unit: '', start: 5, end: 8 }, { type: 'Operator', operator: '-', start: 8, end: 9 }, - { type: 'NumberValue', value: -30, unit: '', start: 9, end: 12 } + { type: 'NumberValue', value: -30, rawValue: '-30', unit: '', start: 9, end: 12 } ]); deepEqual(tokenize('p-10%-20--30'), [ { type: 'Literal', value: 'p', start: 0, end: 1 }, - { type: 'NumberValue', value: -10, unit: '%', start: 1, end: 5 }, - { type: 'NumberValue', value: -20, unit: '', start: 5, end: 8 }, + { type: 'NumberValue', value: -10, rawValue: '-10', unit: '%', start: 1, end: 5 }, + { type: 'NumberValue', value: -20, rawValue: '-20', unit: '', start: 5, end: 8 }, { type: 'Operator', operator: '-', start: 8, end: 9 }, - { type: 'NumberValue', value: -30, unit: '', start: 9, end: 12 } + { type: 'NumberValue', value: -30, rawValue: '-30', unit: '', start: 9, end: 12 } ]); }); it('float values', () => { deepEqual(tokenize('p.5'), [ { type: 'Literal', value: 'p', start: 0, end: 1 }, - { type: 'NumberValue', value: 0.5, unit: '', start: 1, end: 3 } + { type: 'NumberValue', value: 0.5, rawValue: '.5', unit: '', start: 1, end: 3 } ]); deepEqual(tokenize('p-.5'), [ { type: 'Literal', value: 'p', start: 0, end: 1 }, - { type: 'NumberValue', value: -0.5, unit: '', start: 1, end: 4 } + { type: 'NumberValue', value: -0.5, rawValue: '-.5', unit: '', start: 1, end: 4 } ]); deepEqual(tokenize('p.1.2.3'), [ { type: 'Literal', value: 'p', start: 0, end: 1 }, - { type: 'NumberValue', value: 0.1, unit: '', start: 1, end: 3 }, - { type: 'NumberValue', value: 0.2, unit: '', start: 3, end: 5 }, - { type: 'NumberValue', value: 0.3, unit: '', start: 5, end: 7 } + { type: 'NumberValue', value: 0.1, rawValue: '.1', unit: '', start: 1, end: 3 }, + { type: 'NumberValue', value: 0.2, rawValue: '.2', unit: '', start: 3, end: 5 }, + { type: 'NumberValue', value: 0.3, rawValue: '.3', unit: '', start: 5, end: 7 } ]); deepEqual(tokenize('p.1-.2.3'), [ { type: 'Literal', value: 'p', start: 0, end: 1 }, - { type: 'NumberValue', value: 0.1, unit: '', start: 1, end: 3 }, + { type: 'NumberValue', value: 0.1, rawValue: '.1', unit: '', start: 1, end: 3 }, { type: 'Operator', operator: '-', start: 3, end: 4 }, - { type: 'NumberValue', value: 0.2, unit: '', start: 4, end: 6 }, - { type: 'NumberValue', value: 0.3, unit: '', start: 6, end: 8 } + { type: 'NumberValue', value: 0.2, rawValue: '.2', unit: '', start: 4, end: 6 }, + { type: 'NumberValue', value: 0.3, rawValue: '.3', unit: '', start: 6, end: 8 } ]); deepEqual(tokenize('p.1--.2.3'), [ { type: 'Literal', value: 'p', start: 0, end: 1 }, - { type: 'NumberValue', value: 0.1, unit: '', start: 1, end: 3 }, + { type: 'NumberValue', value: 0.1, rawValue: '.1', unit: '', start: 1, end: 3 }, { type: 'Operator', operator: '-', start: 3, end: 4 }, - { type: 'NumberValue', value: -0.2, unit: '', start: 4, end: 7 }, - { type: 'NumberValue', value: 0.3, unit: '', start: 7, end: 9 } + { type: 'NumberValue', value: -0.2, rawValue: '-.2', unit: '', start: 4, end: 7 }, + { type: 'NumberValue', value: 0.3, rawValue: '.3', unit: '', start: 7, end: 9 } ]); deepEqual(tokenize('10'), [ - { type: 'NumberValue', value: 10, unit: '', start: 0, end: 2 }, + { type: 'NumberValue', value: 10, rawValue: '10', unit: '', start: 0, end: 2 }, ]); deepEqual(tokenize('.1'), [ - { type: 'NumberValue', value: 0.1, unit: '', start: 0, end: 2 }, + { type: 'NumberValue', value: 0.1, rawValue: '.1', unit: '', start: 0, end: 2 }, ]); throws(() => tokenize('.foo'), /Unexpected character at 1/); @@ -176,14 +176,14 @@ describe('Tokenizer', () => { { type: 'Literal', value: 'm', start: 0, end: 1 }, { type: 'Operator', operator: '-', start: 1, end: 2 }, { type: 'Literal', value: 'a', start: 2, end: 3 }, - { type: 'NumberValue', value: 0, unit: '', start: 3, end: 4 } + { type: 'NumberValue', value: 0, rawValue: '0', unit: '', start: 3, end: 4 } ]); deepEqual(tokenize('m-a0-a'), [ { type: 'Literal', value: 'm', start: 0, end: 1 }, { type: 'Operator', operator: '-', start: 1, end: 2 }, { type: 'Literal', value: 'a', start: 2, end: 3 }, - { type: 'NumberValue', value: 0, unit: '', start: 3, end: 4 }, + { type: 'NumberValue', value: 0, rawValue: '0', unit: '', start: 3, end: 4 }, { type: 'Operator', operator: '-', start: 4, end: 5 }, { type: 'Literal', value: 'a', start: 5, end: 6 } ]); @@ -201,16 +201,16 @@ describe('Tokenizer', () => { { type: 'WhiteSpace', start: 21, end: 22 }, { type: 'Literal', value: 'rgb', start: 22, end: 25 }, { type: 'Bracket', open: true, start: 25, end: 26 }, - { type: 'NumberValue', value: 0, unit: '', start: 26, end: 27 }, + { type: 'NumberValue', value: 0, rawValue: '0', unit: '', start: 26, end: 27 }, { type: 'Operator', operator: ',', start: 27, end: 28 }, { type: 'WhiteSpace', start: 28, end: 29 }, - { type: 'NumberValue', value: 0, unit: '', start: 29, end: 30 }, + { type: 'NumberValue', value: 0, rawValue: '0', unit: '', start: 29, end: 30 }, { type: 'Operator', operator: ',', start: 30, end: 31 }, { type: 'WhiteSpace', start: 31, end: 32 }, - { type: 'NumberValue', value: 0, unit: '', start: 32, end: 33 }, + { type: 'NumberValue', value: 0, rawValue: '0', unit: '', start: 32, end: 33 }, { type: 'Bracket', open: false, start: 33, end: 34 }, { type: 'WhiteSpace', start: 34, end: 35 }, - { type: 'NumberValue', value: 10, unit: '%', start: 35, end: 38 }, + { type: 'NumberValue', value: 10, rawValue: '10', unit: '%', start: 35, end: 38 }, { type: 'Bracket', open: false, start: 38, end: 39 } ]); }); @@ -227,7 +227,7 @@ describe('Tokenizer', () => { deepEqual(tokenize('p10!'), [ { type: 'Literal', value: 'p', start: 0, end: 1 }, - { type: 'NumberValue', value: 10, unit: '', start: 1, end: 3 }, + { type: 'NumberValue', value: 10, rawValue: '10', unit: '', start: 1, end: 3 }, { type: 'Operator', operator: '!', start: 3, end: 4 } ]); }); @@ -235,7 +235,7 @@ describe('Tokenizer', () => { it('mixed', () => { deepEqual(tokenize('bd1-s#fc0'), [ { type: 'Literal', value: 'bd', start: 0, end: 2 }, - { type: 'NumberValue', value: 1, unit: '', start: 2, end: 3 }, + { type: 'NumberValue', value: 1, rawValue: '1', unit: '', start: 2, end: 3 }, { type: 'Operator', operator: '-', start: 3, end: 4 }, { type: 'Literal', value: 's', start: 4, end: 5 }, { type: 'ColorValue', r: 255, g: 204, b: 0, a: 1, raw: 'fc0', start: 5, end: 9 } @@ -245,24 +245,24 @@ describe('Tokenizer', () => { { type: 'Literal', value: 'bd', start: 0, end: 2 }, { type: 'ColorValue', r: 255, g: 204, b: 0, a: 1, raw: 'fc0', start: 2, end: 6 }, { type: 'Operator', operator: '-', start: 6, end: 7 }, - { type: 'NumberValue', value: 1, unit: '', start: 7, end: 8 } + { type: 'NumberValue', value: 1, rawValue: '1', unit: '', start: 7, end: 8 } ]); deepEqual(tokenize('p0+m0'), [ { type: 'Literal', value: 'p', start: 0, end: 1 }, - { type: 'NumberValue', value: 0, unit: '', start: 1, end: 2 }, + { type: 'NumberValue', value: 0, rawValue: '0', unit: '', start: 1, end: 2 }, { type: 'Operator', operator: '+', start: 2, end: 3 }, { type: 'Literal', value: 'm', start: 3, end: 4 }, - { type: 'NumberValue', value: 0, unit: '', start: 4, end: 5 } + { type: 'NumberValue', value: 0, rawValue: '0', unit: '', start: 4, end: 5 } ]); deepEqual(tokenize('p0!+m0!'), [ { type: 'Literal', value: 'p', start: 0, end: 1 }, - { type: 'NumberValue', value: 0, unit: '', start: 1, end: 2 }, + { type: 'NumberValue', value: 0, rawValue: '0', unit: '', start: 1, end: 2 }, { type: 'Operator', operator: '!', start: 2, end: 3 }, { type: 'Operator', operator: '+', start: 3, end: 4 }, { type: 'Literal', value: 'm', start: 4, end: 5 }, - { type: 'NumberValue', value: 0, unit: '', start: 5, end: 6 }, + { type: 'NumberValue', value: 0, rawValue: '0', unit: '', start: 5, end: 6 }, { type: 'Operator', operator: '!', start: 6, end: 7 } ]); @@ -291,7 +291,7 @@ describe('Tokenizer', () => { deepEqual(tokenize('@k10'), [ { type: 'Literal', value: '@k', start: 0, end: 2 }, - { type: 'NumberValue', value: 10, unit: '', start: 2, end: 4 } + { type: 'NumberValue', value: 10, rawValue: '10', unit: '', start: 2, end: 4 } ]); }); });
43
Support trailing dots in CSS abbreviations
43
.ts
ts
mit
emmetio/emmet
10072276
<NME> tokenizer.ts <BEF> import { deepEqual } from 'assert'; import tokenize from '../src/tokenizer'; describe('Tokenizer', () => { it('numeric values', () => { deepEqual(tokenize('p10'), [ { type: 'Literal', value: 'p', start: 0, end: 1 }, { type: 'NumberValue', value: 10, unit: '', start: 1, end: 3 } ]); deepEqual(tokenize('p-10'), [ { type: 'Literal', value: 'p', start: 0, end: 1 }, { type: 'NumberValue', value: -10, unit: '', start: 1, end: 4 } ]); deepEqual(tokenize('p-10-'), [ { type: 'Literal', value: 'p', start: 0, end: 1 }, { type: 'NumberValue', value: -10, unit: '', start: 1, end: 4 }, { type: 'Operator', operator: '-', start: 4, end: 5 } ]); deepEqual(tokenize('p-10-20'), [ { type: 'Literal', value: 'p', start: 0, end: 1 }, { type: 'NumberValue', value: -10, unit: '', start: 1, end: 4 }, { type: 'Operator', operator: '-', start: 4, end: 5 }, { type: 'NumberValue', value: 20, unit: '', start: 5, end: 7 } ]); deepEqual(tokenize('p-10--20'), [ { type: 'Literal', value: 'p', start: 0, end: 1 }, { type: 'NumberValue', value: -10, unit: '', start: 1, end: 4 }, { type: 'Operator', operator: '-', start: 4, end: 5 }, { type: 'NumberValue', value: -20, unit: '', start: 5, end: 8 } ]); deepEqual(tokenize('p-10-20--30'), [ { type: 'Literal', value: 'p', start: 0, end: 1 }, { type: 'NumberValue', value: -10, unit: '', start: 1, end: 4 }, { type: 'Operator', operator: '-', start: 4, end: 5 }, { type: 'NumberValue', value: 20, unit: '', start: 5, end: 7 }, { type: 'Operator', operator: '-', start: 7, end: 8 }, { type: 'NumberValue', value: -30, unit: '', start: 8, end: 11 } ]); deepEqual(tokenize('p-10p-20--30'), [ { type: 'Literal', value: 'p', start: 0, end: 1 }, { type: 'NumberValue', value: -10, unit: 'p', start: 1, end: 5 }, { type: 'NumberValue', value: -20, unit: '', start: 5, end: 8 }, { type: 'Operator', operator: '-', start: 8, end: 9 }, { type: 'NumberValue', value: -30, unit: '', start: 9, end: 12 } ]); deepEqual(tokenize('p-10%-20--30'), [ { type: 'Literal', value: 'p', start: 0, end: 1 }, { type: 'NumberValue', value: -10, unit: '%', start: 1, end: 5 }, { type: 'NumberValue', value: -20, unit: '', start: 5, end: 8 }, { type: 'Operator', operator: '-', start: 8, end: 9 }, { type: 'NumberValue', value: -30, unit: '', start: 9, end: 12 } ]); }); it('float values', () => { deepEqual(tokenize('p.5'), [ { type: 'Literal', value: 'p', start: 0, end: 1 }, { type: 'NumberValue', value: 0.5, unit: '', start: 1, end: 3 } ]); deepEqual(tokenize('p-.5'), [ { type: 'Literal', value: 'p', start: 0, end: 1 }, { type: 'NumberValue', value: -0.5, unit: '', start: 1, end: 4 } ]); deepEqual(tokenize('p.1.2.3'), [ { type: 'Literal', value: 'p', start: 0, end: 1 }, { type: 'NumberValue', value: 0.1, unit: '', start: 1, end: 3 }, { type: 'NumberValue', value: 0.2, unit: '', start: 3, end: 5 }, { type: 'NumberValue', value: 0.3, unit: '', start: 5, end: 7 } ]); deepEqual(tokenize('p.1-.2.3'), [ { type: 'Literal', value: 'p', start: 0, end: 1 }, { type: 'NumberValue', value: 0.1, unit: '', start: 1, end: 3 }, { type: 'Operator', operator: '-', start: 3, end: 4 }, { type: 'NumberValue', value: 0.2, unit: '', start: 4, end: 6 }, { type: 'NumberValue', value: 0.3, unit: '', start: 6, end: 8 } ]); deepEqual(tokenize('p.1--.2.3'), [ { type: 'Literal', value: 'p', start: 0, end: 1 }, { type: 'NumberValue', value: 0.1, unit: '', start: 1, end: 3 }, { type: 'Operator', operator: '-', start: 3, end: 4 }, { type: 'NumberValue', value: -0.2, unit: '', start: 4, end: 7 }, { type: 'NumberValue', value: 0.3, unit: '', start: 7, end: 9 } ]); deepEqual(tokenize('10'), [ { type: 'NumberValue', value: 10, unit: '', start: 0, end: 2 }, ]); deepEqual(tokenize('.1'), [ { type: 'NumberValue', value: 0.1, unit: '', start: 0, end: 2 }, ]); throws(() => tokenize('.foo'), /Unexpected character at 1/); // throws(() => tokenize('.foo'), /Unexpected character at 1/); }); it('color values', () => { deepEqual(tokenize('c#'), [ { type: 'Literal', value: 'c', start: 0, end: 1 }, { type: 'ColorValue', r: 0, g: 0, b: 0, a: 1, raw: '', start: 1, end: 2 } ]); deepEqual(tokenize('c#1'), [ { type: 'Literal', value: 'c', start: 0, end: 1 }, { type: 'ColorValue', r: 17, g: 17, b: 17, a: 1, raw: '1', start: 1, end: 3 } ]); deepEqual(tokenize('c#.'), [ { type: 'Literal', value: 'c', start: 0, end: 1 }, { type: 'ColorValue', r: 0, g: 0, b: 0, a: 1, raw: '.', start: 1, end: 3 } ]); deepEqual(tokenize('c#f'), [ { type: 'Literal', value: 'c', start: 0, end: 1 }, { type: 'ColorValue', r: 255, g: 255, b: 255, a: 1, raw: 'f', start: 1, end: 3 } ]); deepEqual(tokenize('c#a#b#c'), [ { type: 'Literal', value: 'c', start: 0, end: 1 }, { type: 'ColorValue', r: 170, g: 170, b: 170, a: 1, raw: 'a', start: 1, end: 3 }, { type: 'ColorValue', r: 187, g: 187, b: 187, a: 1, raw: 'b', start: 3, end: 5 }, { type: 'ColorValue', r: 204, g: 204, b: 204, a: 1, raw: 'c', start: 5, end: 7 } ]); deepEqual(tokenize('c#af'), [ { type: 'Literal', value: 'c', start: 0, end: 1 }, { type: 'ColorValue', r: 175, g: 175, b: 175, a: 1, raw: 'af', start: 1, end: 4 } ]); deepEqual(tokenize('c#fc0'), [ { type: 'Literal', value: 'c', start: 0, end: 1 }, { type: 'ColorValue', r: 255, g: 204, b: 0, a: 1, raw: 'fc0', start: 1, end: 5 } ]); deepEqual(tokenize('c#11.5'), [ { type: 'Literal', value: 'c', start: 0, end: 1 }, { type: 'ColorValue', r: 17, g: 17, b: 17, a: 0.5, raw: '11.5', start: 1, end: 6 } ]); deepEqual(tokenize('c#.99'), [ { type: 'Literal', value: 'c', start: 0, end: 1 }, { type: 'ColorValue', r: 0, g: 0, b: 0, a: 0.99, raw: '.99', start: 1, end: 5 } ]); deepEqual(tokenize('c#t'), [ { type: 'Literal', value: 'c', start: 0, end: 1 }, { type: 'ColorValue', r: 0, g: 0, b: 0, a: 0, raw: 't', start: 1, end: 3 } ]); deepEqual(tokenize('c#${fff}'), [ { type: 'Literal', value: 'c', start: 0, end: 1 }, { type: 'Literal', value: '#', start: 1, end: 2 }, { type: 'Field', index: undefined, name: 'fff', start: 2, end: 8 } ]); }); it('keywords', () => { deepEqual(tokenize('m:a'), [ { type: 'Literal', value: 'm', start: 0, end: 1 }, { type: 'Operator', operator: ':', start: 1, end: 2 }, { type: 'Literal', value: 'a', start: 2, end: 3 } ]); deepEqual(tokenize('m-a'), [ { type: 'Literal', value: 'm', start: 0, end: 1 }, { type: 'Operator', operator: '-', start: 1, end: 2 }, { type: 'Literal', value: 'a', start: 2, end: 3 }, { type: 'NumberValue', value: 0, unit: '', start: 3, end: 4 } ]); deepEqual(tokenize('m-a0-a'), [ { type: 'Literal', value: 'm', start: 0, end: 1 }, { type: 'Operator', operator: '-', start: 1, end: 2 }, { type: 'Literal', value: 'a', start: 2, end: 3 }, { type: 'NumberValue', value: 0, unit: '', start: 3, end: 4 }, { type: 'Operator', operator: '-', start: 4, end: 5 }, { type: 'Literal', value: 'a', start: 5, end: 6 } ]); { type: 'Literal', value: 'a', start: 2, end: 3 }, { type: 'NumberValue', value: 0, rawValue: '0', unit: '', start: 3, end: 4 } ]); deepEqual(tokenize('m-a0-a'), [ { type: 'Literal', value: 'm', start: 0, end: 1 }, { type: 'Operator', operator: '-', start: 1, end: 2 }, { type: 'Literal', value: 'a', start: 2, end: 3 }, { type: 'NumberValue', value: 0, rawValue: '0', unit: '', start: 3, end: 4 }, { type: 'Operator', operator: '-', start: 4, end: 5 }, { type: 'Literal', value: 'a', start: 5, end: 6 } { type: 'WhiteSpace', start: 21, end: 22 }, { type: 'Literal', value: 'rgb', start: 22, end: 25 }, { type: 'Bracket', open: true, start: 25, end: 26 }, { type: 'NumberValue', value: 0, unit: '', start: 26, end: 27 }, { type: 'Operator', operator: ',', start: 27, end: 28 }, { type: 'WhiteSpace', start: 28, end: 29 }, { type: 'NumberValue', value: 0, unit: '', start: 29, end: 30 }, { type: 'Operator', operator: ',', start: 30, end: 31 }, { type: 'WhiteSpace', start: 31, end: 32 }, { type: 'NumberValue', value: 0, unit: '', start: 32, end: 33 }, { type: 'Bracket', open: false, start: 33, end: 34 }, { type: 'WhiteSpace', start: 34, end: 35 }, { type: 'NumberValue', value: 10, unit: '%', start: 35, end: 38 }, { type: 'Bracket', open: false, start: 38, end: 39 } ]); }); { type: 'Operator', operator: ',', start: 27, end: 28 }, { type: 'WhiteSpace', start: 28, end: 29 }, { type: 'NumberValue', value: 0, rawValue: '0', unit: '', start: 29, end: 30 }, { type: 'Operator', operator: ',', start: 30, end: 31 }, { type: 'WhiteSpace', start: 31, end: 32 }, { type: 'NumberValue', value: 0, rawValue: '0', unit: '', start: 32, end: 33 }, { type: 'Bracket', open: false, start: 33, end: 34 }, { type: 'WhiteSpace', start: 34, end: 35 }, { type: 'NumberValue', value: 10, rawValue: '10', unit: '%', start: 35, end: 38 }, { type: 'Bracket', open: false, start: 38, end: 39 } deepEqual(tokenize('p10!'), [ { type: 'Literal', value: 'p', start: 0, end: 1 }, { type: 'NumberValue', value: 10, unit: '', start: 1, end: 3 }, { type: 'Operator', operator: '!', start: 3, end: 4 } ]); }); it('mixed', () => { deepEqual(tokenize('bd1-s#fc0'), [ { type: 'Literal', value: 'bd', start: 0, end: 2 }, { type: 'NumberValue', value: 1, unit: '', start: 2, end: 3 }, { type: 'Operator', operator: '-', start: 3, end: 4 }, { type: 'Literal', value: 's', start: 4, end: 5 }, { type: 'ColorValue', r: 255, g: 204, b: 0, a: 1, raw: 'fc0', start: 5, end: 9 } { type: 'NumberValue', value: 10, rawValue: '10', unit: '', start: 1, end: 3 }, { type: 'Operator', operator: '!', start: 3, end: 4 } ]); { type: 'Literal', value: 'bd', start: 0, end: 2 }, { type: 'ColorValue', r: 255, g: 204, b: 0, a: 1, raw: 'fc0', start: 2, end: 6 }, { type: 'Operator', operator: '-', start: 6, end: 7 }, { type: 'NumberValue', value: 1, unit: '', start: 7, end: 8 } ]); deepEqual(tokenize('p0+m0'), [ { type: 'Literal', value: 'p', start: 0, end: 1 }, { type: 'NumberValue', value: 0, unit: '', start: 1, end: 2 }, { type: 'Operator', operator: '+', start: 2, end: 3 }, { type: 'Literal', value: 'm', start: 3, end: 4 }, { type: 'NumberValue', value: 0, unit: '', start: 4, end: 5 } ]); deepEqual(tokenize('p0!+m0!'), [ { type: 'Literal', value: 'p', start: 0, end: 1 }, { type: 'NumberValue', value: 0, unit: '', start: 1, end: 2 }, { type: 'Operator', operator: '!', start: 2, end: 3 }, { type: 'Operator', operator: '+', start: 3, end: 4 }, { type: 'Literal', value: 'm', start: 4, end: 5 }, { type: 'NumberValue', value: 0, unit: '', start: 5, end: 6 }, { type: 'Operator', operator: '!', start: 6, end: 7 } ]); ]); deepEqual(tokenize('p0!+m0!'), [ { type: 'Literal', value: 'p', start: 0, end: 1 }, { type: 'NumberValue', value: 0, rawValue: '0', unit: '', start: 1, end: 2 }, { type: 'Operator', operator: '!', start: 2, end: 3 }, { type: 'Operator', operator: '+', start: 3, end: 4 }, { type: 'Literal', value: 'm', start: 4, end: 5 }, { type: 'NumberValue', value: 0, rawValue: '0', unit: '', start: 5, end: 6 }, { type: 'Operator', operator: '!', start: 6, end: 7 } ]); deepEqual(tokenize('${2:0}%'), [ { type: 'Field', index: 2, name: '0', start: 0, end: 6 }, { type: 'Literal', value: '%', start: 6, end: 7 } ]); deepEqual(tokenize('.${1:5}'), [ { type: 'Literal', value: '.', start: 0, end: 1 }, { type: 'Field', index: 1, name: '5', start: 1, end: 7 }, ]); }); deepEqual(tokenize('@k10'), [ { type: 'Literal', value: '@k', start: 0, end: 2 }, { type: 'NumberValue', value: 10, unit: '', start: 2, end: 4 } ]); }); }); deepEqual(tokenize('foo$bar-2'), [ { type: 'Literal', value: 'foo', start: 0, end: 3 }, { type: 'Literal', value: '$bar-2', start: 3, end: 9 } ]); deepEqual(tokenize('foo$bar@bam'), [ { type: 'Literal', value: 'foo', start: 0, end: 3 }, { type: 'Literal', value: '$bar', start: 3, end: 7 }, { type: 'Literal', value: '@bam', start: 7, end: 11 } ]); deepEqual(tokenize('@k10'), [ { type: 'Literal', value: '@k', start: 0, end: 2 }, { type: 'NumberValue', value: 10, rawValue: '10', unit: '', start: 2, end: 4 } ]); }); }); <MSG> Support trailing dots in CSS abbreviations <DFF> @@ -5,100 +5,100 @@ describe('Tokenizer', () => { it('numeric values', () => { deepEqual(tokenize('p10'), [ { type: 'Literal', value: 'p', start: 0, end: 1 }, - { type: 'NumberValue', value: 10, unit: '', start: 1, end: 3 } + { type: 'NumberValue', value: 10, rawValue: '10', unit: '', start: 1, end: 3 } ]); deepEqual(tokenize('p-10'), [ { type: 'Literal', value: 'p', start: 0, end: 1 }, - { type: 'NumberValue', value: -10, unit: '', start: 1, end: 4 } + { type: 'NumberValue', value: -10, rawValue: '-10', unit: '', start: 1, end: 4 } ]); deepEqual(tokenize('p-10-'), [ { type: 'Literal', value: 'p', start: 0, end: 1 }, - { type: 'NumberValue', value: -10, unit: '', start: 1, end: 4 }, + { type: 'NumberValue', value: -10, rawValue: '-10', unit: '', start: 1, end: 4 }, { type: 'Operator', operator: '-', start: 4, end: 5 } ]); deepEqual(tokenize('p-10-20'), [ { type: 'Literal', value: 'p', start: 0, end: 1 }, - { type: 'NumberValue', value: -10, unit: '', start: 1, end: 4 }, + { type: 'NumberValue', value: -10, rawValue: '-10', unit: '', start: 1, end: 4 }, { type: 'Operator', operator: '-', start: 4, end: 5 }, - { type: 'NumberValue', value: 20, unit: '', start: 5, end: 7 } + { type: 'NumberValue', value: 20, rawValue: '20', unit: '', start: 5, end: 7 } ]); deepEqual(tokenize('p-10--20'), [ { type: 'Literal', value: 'p', start: 0, end: 1 }, - { type: 'NumberValue', value: -10, unit: '', start: 1, end: 4 }, + { type: 'NumberValue', value: -10, rawValue: '-10', unit: '', start: 1, end: 4 }, { type: 'Operator', operator: '-', start: 4, end: 5 }, - { type: 'NumberValue', value: -20, unit: '', start: 5, end: 8 } + { type: 'NumberValue', value: -20, rawValue: '-20', unit: '', start: 5, end: 8 } ]); deepEqual(tokenize('p-10-20--30'), [ { type: 'Literal', value: 'p', start: 0, end: 1 }, - { type: 'NumberValue', value: -10, unit: '', start: 1, end: 4 }, + { type: 'NumberValue', value: -10, rawValue: '-10', unit: '', start: 1, end: 4 }, { type: 'Operator', operator: '-', start: 4, end: 5 }, - { type: 'NumberValue', value: 20, unit: '', start: 5, end: 7 }, + { type: 'NumberValue', value: 20, rawValue: '20', unit: '', start: 5, end: 7 }, { type: 'Operator', operator: '-', start: 7, end: 8 }, - { type: 'NumberValue', value: -30, unit: '', start: 8, end: 11 } + { type: 'NumberValue', value: -30, rawValue: '-30', unit: '', start: 8, end: 11 } ]); deepEqual(tokenize('p-10p-20--30'), [ { type: 'Literal', value: 'p', start: 0, end: 1 }, - { type: 'NumberValue', value: -10, unit: 'p', start: 1, end: 5 }, - { type: 'NumberValue', value: -20, unit: '', start: 5, end: 8 }, + { type: 'NumberValue', value: -10, rawValue: '-10', unit: 'p', start: 1, end: 5 }, + { type: 'NumberValue', value: -20, rawValue: '-20', unit: '', start: 5, end: 8 }, { type: 'Operator', operator: '-', start: 8, end: 9 }, - { type: 'NumberValue', value: -30, unit: '', start: 9, end: 12 } + { type: 'NumberValue', value: -30, rawValue: '-30', unit: '', start: 9, end: 12 } ]); deepEqual(tokenize('p-10%-20--30'), [ { type: 'Literal', value: 'p', start: 0, end: 1 }, - { type: 'NumberValue', value: -10, unit: '%', start: 1, end: 5 }, - { type: 'NumberValue', value: -20, unit: '', start: 5, end: 8 }, + { type: 'NumberValue', value: -10, rawValue: '-10', unit: '%', start: 1, end: 5 }, + { type: 'NumberValue', value: -20, rawValue: '-20', unit: '', start: 5, end: 8 }, { type: 'Operator', operator: '-', start: 8, end: 9 }, - { type: 'NumberValue', value: -30, unit: '', start: 9, end: 12 } + { type: 'NumberValue', value: -30, rawValue: '-30', unit: '', start: 9, end: 12 } ]); }); it('float values', () => { deepEqual(tokenize('p.5'), [ { type: 'Literal', value: 'p', start: 0, end: 1 }, - { type: 'NumberValue', value: 0.5, unit: '', start: 1, end: 3 } + { type: 'NumberValue', value: 0.5, rawValue: '.5', unit: '', start: 1, end: 3 } ]); deepEqual(tokenize('p-.5'), [ { type: 'Literal', value: 'p', start: 0, end: 1 }, - { type: 'NumberValue', value: -0.5, unit: '', start: 1, end: 4 } + { type: 'NumberValue', value: -0.5, rawValue: '-.5', unit: '', start: 1, end: 4 } ]); deepEqual(tokenize('p.1.2.3'), [ { type: 'Literal', value: 'p', start: 0, end: 1 }, - { type: 'NumberValue', value: 0.1, unit: '', start: 1, end: 3 }, - { type: 'NumberValue', value: 0.2, unit: '', start: 3, end: 5 }, - { type: 'NumberValue', value: 0.3, unit: '', start: 5, end: 7 } + { type: 'NumberValue', value: 0.1, rawValue: '.1', unit: '', start: 1, end: 3 }, + { type: 'NumberValue', value: 0.2, rawValue: '.2', unit: '', start: 3, end: 5 }, + { type: 'NumberValue', value: 0.3, rawValue: '.3', unit: '', start: 5, end: 7 } ]); deepEqual(tokenize('p.1-.2.3'), [ { type: 'Literal', value: 'p', start: 0, end: 1 }, - { type: 'NumberValue', value: 0.1, unit: '', start: 1, end: 3 }, + { type: 'NumberValue', value: 0.1, rawValue: '.1', unit: '', start: 1, end: 3 }, { type: 'Operator', operator: '-', start: 3, end: 4 }, - { type: 'NumberValue', value: 0.2, unit: '', start: 4, end: 6 }, - { type: 'NumberValue', value: 0.3, unit: '', start: 6, end: 8 } + { type: 'NumberValue', value: 0.2, rawValue: '.2', unit: '', start: 4, end: 6 }, + { type: 'NumberValue', value: 0.3, rawValue: '.3', unit: '', start: 6, end: 8 } ]); deepEqual(tokenize('p.1--.2.3'), [ { type: 'Literal', value: 'p', start: 0, end: 1 }, - { type: 'NumberValue', value: 0.1, unit: '', start: 1, end: 3 }, + { type: 'NumberValue', value: 0.1, rawValue: '.1', unit: '', start: 1, end: 3 }, { type: 'Operator', operator: '-', start: 3, end: 4 }, - { type: 'NumberValue', value: -0.2, unit: '', start: 4, end: 7 }, - { type: 'NumberValue', value: 0.3, unit: '', start: 7, end: 9 } + { type: 'NumberValue', value: -0.2, rawValue: '-.2', unit: '', start: 4, end: 7 }, + { type: 'NumberValue', value: 0.3, rawValue: '.3', unit: '', start: 7, end: 9 } ]); deepEqual(tokenize('10'), [ - { type: 'NumberValue', value: 10, unit: '', start: 0, end: 2 }, + { type: 'NumberValue', value: 10, rawValue: '10', unit: '', start: 0, end: 2 }, ]); deepEqual(tokenize('.1'), [ - { type: 'NumberValue', value: 0.1, unit: '', start: 0, end: 2 }, + { type: 'NumberValue', value: 0.1, rawValue: '.1', unit: '', start: 0, end: 2 }, ]); throws(() => tokenize('.foo'), /Unexpected character at 1/); @@ -176,14 +176,14 @@ describe('Tokenizer', () => { { type: 'Literal', value: 'm', start: 0, end: 1 }, { type: 'Operator', operator: '-', start: 1, end: 2 }, { type: 'Literal', value: 'a', start: 2, end: 3 }, - { type: 'NumberValue', value: 0, unit: '', start: 3, end: 4 } + { type: 'NumberValue', value: 0, rawValue: '0', unit: '', start: 3, end: 4 } ]); deepEqual(tokenize('m-a0-a'), [ { type: 'Literal', value: 'm', start: 0, end: 1 }, { type: 'Operator', operator: '-', start: 1, end: 2 }, { type: 'Literal', value: 'a', start: 2, end: 3 }, - { type: 'NumberValue', value: 0, unit: '', start: 3, end: 4 }, + { type: 'NumberValue', value: 0, rawValue: '0', unit: '', start: 3, end: 4 }, { type: 'Operator', operator: '-', start: 4, end: 5 }, { type: 'Literal', value: 'a', start: 5, end: 6 } ]); @@ -201,16 +201,16 @@ describe('Tokenizer', () => { { type: 'WhiteSpace', start: 21, end: 22 }, { type: 'Literal', value: 'rgb', start: 22, end: 25 }, { type: 'Bracket', open: true, start: 25, end: 26 }, - { type: 'NumberValue', value: 0, unit: '', start: 26, end: 27 }, + { type: 'NumberValue', value: 0, rawValue: '0', unit: '', start: 26, end: 27 }, { type: 'Operator', operator: ',', start: 27, end: 28 }, { type: 'WhiteSpace', start: 28, end: 29 }, - { type: 'NumberValue', value: 0, unit: '', start: 29, end: 30 }, + { type: 'NumberValue', value: 0, rawValue: '0', unit: '', start: 29, end: 30 }, { type: 'Operator', operator: ',', start: 30, end: 31 }, { type: 'WhiteSpace', start: 31, end: 32 }, - { type: 'NumberValue', value: 0, unit: '', start: 32, end: 33 }, + { type: 'NumberValue', value: 0, rawValue: '0', unit: '', start: 32, end: 33 }, { type: 'Bracket', open: false, start: 33, end: 34 }, { type: 'WhiteSpace', start: 34, end: 35 }, - { type: 'NumberValue', value: 10, unit: '%', start: 35, end: 38 }, + { type: 'NumberValue', value: 10, rawValue: '10', unit: '%', start: 35, end: 38 }, { type: 'Bracket', open: false, start: 38, end: 39 } ]); }); @@ -227,7 +227,7 @@ describe('Tokenizer', () => { deepEqual(tokenize('p10!'), [ { type: 'Literal', value: 'p', start: 0, end: 1 }, - { type: 'NumberValue', value: 10, unit: '', start: 1, end: 3 }, + { type: 'NumberValue', value: 10, rawValue: '10', unit: '', start: 1, end: 3 }, { type: 'Operator', operator: '!', start: 3, end: 4 } ]); }); @@ -235,7 +235,7 @@ describe('Tokenizer', () => { it('mixed', () => { deepEqual(tokenize('bd1-s#fc0'), [ { type: 'Literal', value: 'bd', start: 0, end: 2 }, - { type: 'NumberValue', value: 1, unit: '', start: 2, end: 3 }, + { type: 'NumberValue', value: 1, rawValue: '1', unit: '', start: 2, end: 3 }, { type: 'Operator', operator: '-', start: 3, end: 4 }, { type: 'Literal', value: 's', start: 4, end: 5 }, { type: 'ColorValue', r: 255, g: 204, b: 0, a: 1, raw: 'fc0', start: 5, end: 9 } @@ -245,24 +245,24 @@ describe('Tokenizer', () => { { type: 'Literal', value: 'bd', start: 0, end: 2 }, { type: 'ColorValue', r: 255, g: 204, b: 0, a: 1, raw: 'fc0', start: 2, end: 6 }, { type: 'Operator', operator: '-', start: 6, end: 7 }, - { type: 'NumberValue', value: 1, unit: '', start: 7, end: 8 } + { type: 'NumberValue', value: 1, rawValue: '1', unit: '', start: 7, end: 8 } ]); deepEqual(tokenize('p0+m0'), [ { type: 'Literal', value: 'p', start: 0, end: 1 }, - { type: 'NumberValue', value: 0, unit: '', start: 1, end: 2 }, + { type: 'NumberValue', value: 0, rawValue: '0', unit: '', start: 1, end: 2 }, { type: 'Operator', operator: '+', start: 2, end: 3 }, { type: 'Literal', value: 'm', start: 3, end: 4 }, - { type: 'NumberValue', value: 0, unit: '', start: 4, end: 5 } + { type: 'NumberValue', value: 0, rawValue: '0', unit: '', start: 4, end: 5 } ]); deepEqual(tokenize('p0!+m0!'), [ { type: 'Literal', value: 'p', start: 0, end: 1 }, - { type: 'NumberValue', value: 0, unit: '', start: 1, end: 2 }, + { type: 'NumberValue', value: 0, rawValue: '0', unit: '', start: 1, end: 2 }, { type: 'Operator', operator: '!', start: 2, end: 3 }, { type: 'Operator', operator: '+', start: 3, end: 4 }, { type: 'Literal', value: 'm', start: 4, end: 5 }, - { type: 'NumberValue', value: 0, unit: '', start: 5, end: 6 }, + { type: 'NumberValue', value: 0, rawValue: '0', unit: '', start: 5, end: 6 }, { type: 'Operator', operator: '!', start: 6, end: 7 } ]); @@ -291,7 +291,7 @@ describe('Tokenizer', () => { deepEqual(tokenize('@k10'), [ { type: 'Literal', value: '@k', start: 0, end: 2 }, - { type: 'NumberValue', value: 10, unit: '', start: 2, end: 4 } + { type: 'NumberValue', value: 10, rawValue: '10', unit: '', start: 2, end: 4 } ]); }); });
43
Support trailing dots in CSS abbreviations
43
.ts
ts
mit
emmetio/emmet
10072277
<NME> snippets.ts <BEF> import parse, { CSSValue, ParseOptions, FunctionCall, Literal } from '@emmetio/css-abbreviation'; export type CSSSnippet = CSSSnippetRaw | CSSSnippetProperty; interface KeywordMap { [name: string]: FunctionCall | Literal; } export const enum CSSSnippetType { Raw = 'Raw', Property = 'Property' } interface CSSSnippetBase { type: CSSSnippetType; key: string; } export interface CSSSnippetRaw extends CSSSnippetBase { type: CSSSnippetType.Raw; value: string; } export interface CSSSnippetProperty extends CSSSnippetBase { type: CSSSnippetType.Property; property: string; value: CSSValue[][]; keywords: KeywordMap; dependencies: CSSSnippetProperty[]; } const reProperty = /^([a-z-]+)(?:\s*:\s*([^\n\r;]+?);*)?$/; const opt: ParseOptions = { value: true }; /** * Creates structure for holding resolved CSS snippet */ export default function createSnippet(key: string, value: string): CSSSnippet { // A snippet could be a raw text snippet (e.g. arbitrary text string) or a // CSS property with possible values separated by `|`. // In latter case, we have to parse snippet as CSS abbreviation const m = value.match(reProperty); if (m) { const keywords: KeywordMap = {}; const parsed: CSSValue[][] = m[2] ? m[2].split('|').map(parseValue) : []; for (const item of parsed) { for (const cssVal of item) { collectKeywords(cssVal, keywords); } } return { type: CSSSnippetType.Property, key, property: m[1], value: parsed, keywords, dependencies: [] }; } return { type: CSSSnippetType.Raw, key, value }; } /** * Nests more specific CSS properties into shorthand ones, e.g. * `background-position-x` -> `background-position` -> `background` */ export function nest(snippets: CSSSnippet[]): CSSSnippet[] { snippets = snippets.sort(snippetsSort); const stack: CSSSnippetProperty[] = []; let prev: CSSSnippet; // For sorted list of CSS properties, create dependency graph where each // shorthand property contains its more specific one, e.g. // background -> background-position -> background-position-x for (const cur of snippets.filter(isProperty)) { // Check if current property belongs to one from parent stack. // Since `snippets` array is sorted, items are perfectly aligned // from shorthands to more specific variants while (stack.length) { prev = stack[stack.length - 1]; if (cur.property.startsWith(prev.property!) && cur.property.charCodeAt(prev.property!.length) === 45 /* - */) { prev.dependencies.push(cur); stack.push(cur); break; } stack.pop(); } if (!stack.length) { stack.push(cur); } } return snippets; } /** * A sorting function for array of snippets */ function snippetsSort(a: CSSSnippet, b: CSSSnippet): number { if (a.key === b.key) { return 0; } return a.key < b.key ? -1 : 1; } function parseValue(value: string): CSSValue[] { return parse(value.trim(), opt)[0].value; } function isProperty(snippet: CSSSnippet): snippet is CSSSnippetProperty { return snippet.type === CSSSnippetType.Property; } function collectKeywords(cssVal: CSSValue, dest: KeywordMap) { for (const v of cssVal.value) { if (v.type === 'Literal') { dest[v.value] = v; } else if (v.type === 'FunctionCall') { dest[v.name] = v; } else if (v.type === 'Field') { // Create literal from field, if available const value = v.name.trim(); if (value) { dest[value] = { type: 'Literal', value }; } } } } <MSG> Minor improvements <DFF> @@ -68,7 +68,7 @@ export default function createSnippet(key: string, value: string): CSSSnippet { * `background-position-x` -> `background-position` -> `background` */ export function nest(snippets: CSSSnippet[]): CSSSnippet[] { - snippets = snippets.sort(snippetsSort); + snippets = snippets.slice().sort(snippetsSort); const stack: CSSSnippetProperty[] = []; let prev: CSSSnippet;
1
Minor improvements
1
.ts
ts
mit
emmetio/emmet
10072278
<NME> snippets.ts <BEF> import parse, { CSSValue, ParseOptions, FunctionCall, Literal } from '@emmetio/css-abbreviation'; export type CSSSnippet = CSSSnippetRaw | CSSSnippetProperty; interface KeywordMap { [name: string]: FunctionCall | Literal; } export const enum CSSSnippetType { Raw = 'Raw', Property = 'Property' } interface CSSSnippetBase { type: CSSSnippetType; key: string; } export interface CSSSnippetRaw extends CSSSnippetBase { type: CSSSnippetType.Raw; value: string; } export interface CSSSnippetProperty extends CSSSnippetBase { type: CSSSnippetType.Property; property: string; value: CSSValue[][]; keywords: KeywordMap; dependencies: CSSSnippetProperty[]; } const reProperty = /^([a-z-]+)(?:\s*:\s*([^\n\r;]+?);*)?$/; const opt: ParseOptions = { value: true }; /** * Creates structure for holding resolved CSS snippet */ export default function createSnippet(key: string, value: string): CSSSnippet { // A snippet could be a raw text snippet (e.g. arbitrary text string) or a // CSS property with possible values separated by `|`. // In latter case, we have to parse snippet as CSS abbreviation const m = value.match(reProperty); if (m) { const keywords: KeywordMap = {}; const parsed: CSSValue[][] = m[2] ? m[2].split('|').map(parseValue) : []; for (const item of parsed) { for (const cssVal of item) { collectKeywords(cssVal, keywords); } } return { type: CSSSnippetType.Property, key, property: m[1], value: parsed, keywords, dependencies: [] }; } return { type: CSSSnippetType.Raw, key, value }; } /** * Nests more specific CSS properties into shorthand ones, e.g. * `background-position-x` -> `background-position` -> `background` */ export function nest(snippets: CSSSnippet[]): CSSSnippet[] { snippets = snippets.sort(snippetsSort); const stack: CSSSnippetProperty[] = []; let prev: CSSSnippet; // For sorted list of CSS properties, create dependency graph where each // shorthand property contains its more specific one, e.g. // background -> background-position -> background-position-x for (const cur of snippets.filter(isProperty)) { // Check if current property belongs to one from parent stack. // Since `snippets` array is sorted, items are perfectly aligned // from shorthands to more specific variants while (stack.length) { prev = stack[stack.length - 1]; if (cur.property.startsWith(prev.property!) && cur.property.charCodeAt(prev.property!.length) === 45 /* - */) { prev.dependencies.push(cur); stack.push(cur); break; } stack.pop(); } if (!stack.length) { stack.push(cur); } } return snippets; } /** * A sorting function for array of snippets */ function snippetsSort(a: CSSSnippet, b: CSSSnippet): number { if (a.key === b.key) { return 0; } return a.key < b.key ? -1 : 1; } function parseValue(value: string): CSSValue[] { return parse(value.trim(), opt)[0].value; } function isProperty(snippet: CSSSnippet): snippet is CSSSnippetProperty { return snippet.type === CSSSnippetType.Property; } function collectKeywords(cssVal: CSSValue, dest: KeywordMap) { for (const v of cssVal.value) { if (v.type === 'Literal') { dest[v.value] = v; } else if (v.type === 'FunctionCall') { dest[v.name] = v; } else if (v.type === 'Field') { // Create literal from field, if available const value = v.name.trim(); if (value) { dest[value] = { type: 'Literal', value }; } } } } <MSG> Minor improvements <DFF> @@ -68,7 +68,7 @@ export default function createSnippet(key: string, value: string): CSSSnippet { * `background-position-x` -> `background-position` -> `background` */ export function nest(snippets: CSSSnippet[]): CSSSnippet[] { - snippets = snippets.sort(snippetsSort); + snippets = snippets.slice().sort(snippetsSort); const stack: CSSSnippetProperty[] = []; let prev: CSSSnippet;
1
Minor improvements
1
.ts
ts
mit
emmetio/emmet
10072279
<NME> jquery.meow.js <BEF> (function ($, window) { 'use strict'; // Meow queue var default_meow_area, meows = { queue: {}, add: function (meow) { this.queue[meow.timestamp] = meow; }, get: function (timestamp) { return this.queue[timestamp]; }, remove: function (timestamp) { delete this.queue[timestamp]; }, size: function () { var timestamp, size = 0; for (timestamp in this.queue) { if (this.queue.hasOwnProperty(timestamp)) { size += 1; } } return size; } }, // Meow constructor Meow = function (options) { var that = this; this.timestamp = new Date().getTime(); // used to identify this meow and timeout this.hovered = false; // whether mouse is over or not if (typeof default_meow_area === 'undefined' && typeof options.container === 'undefined') { default_meow_area = $(window.document.createElement('div')) .attr({'id': ((new Date()).getTime()), 'class': 'meows'}); $('body').prepend(default_meow_area); } if (meows.size() <= 0) { if (typeof options.beforeCreateFirst === 'function') { options.beforeCreateFirst.call(that); } } if (typeof options.container === 'string') { this.container = $(options.container); } else { this.container = default_meow_area; } if (typeof options.title === 'string') { this.title = options.title; } if (typeof options.message === 'string') { this.message = options.message; } else if (options.message instanceof $) { if (options.message.is('input,textarea,select')) { this.message = options.message.val(); } else { this.message = options.message.text(); } if (typeof this.title === 'undefined' && typeof options.message.attr('title') === 'string') { this.title = options.message.attr('title'); } } if (typeof options.icon === 'string') { this.icon = options.icon; } if (options.sticky) { this.duration = Infinity; } else { this.duration = options.duration || 5000; } // Call callback if it's defined (this = meow object) if (typeof options.beforeCreate === 'function') { options.beforeCreate.call(that); } // Add the meow to the meow area this.container.append($(window.document.createElement('div')) .attr('id', 'meow-' + this.timestamp.toString()) .addClass('meow') .html($(window.document.createElement('div')).addClass('inner').html(this.message)) .hide() .fadeIn(400)); this.manifest = $('#meow-' + this.timestamp.toString()); // Add title if it's defined if (typeof this.title === 'string') { this.manifest.find('.inner').prepend( $(window.document.createElement('h1')).text(this.title) ); } // Add icon if it's defined if (typeof that.icon === 'string') { this.manifest.find('.inner').prepend( $(window.document.createElement('div')).addClass('icon').html( $(window.document.createElement('img')).attr('src', this.icon) ) ); } // Add close button if the meow isn't uncloseable // TODO: this close button needs to be much prettier if (options.closeable !== false) { this.manifest.find('.inner').prepend( $(window.document.createElement('a')) .addClass('close') .html('&times;') .attr('href', '#close-meow-' + that.timestamp) .click(function (e) { e.preventDefault(); that.destroy(); }) ); } this.manifest.bind('mouseenter mouseleave', function (event) { if (event.type === 'mouseleave') { that.hovered = false; that.manifest.removeClass('hover'); // Destroy the mow on mouseleave if it's timed out if (that.timestamp + that.duration <= new Date().getTime()) { that.destroy(); } } else { that.hovered = true; that.manifest.addClass('hover'); } }); // Add a timeout if the duration isn't Infinity if (this.duration !== Infinity) { this.timeout = window.setTimeout(function () { // Make sure this meow hasn't already been destroyed if (typeof meows.get(that.timestamp) !== 'undefined') { // Call callback if it's defined (this = meow DOM element) if (typeof options.onTimeout === 'function') { options.onTimeout.call(that.manifest); } // Don't destroy if user is hovering over meow if (that.hovered !== true && typeof that === 'object') { that.destroy(); } } }, that.duration); } this.destroy = function () { if (that.destroyed !== true) { // Call callback if it's defined (this = meow DOM element) if (typeof options.beforeDestroy === 'function') { options.beforeDestroy.call(that.manifest); } that.manifest.find('.inner').fadeTo(400, 0, function () { that.manifest.slideUp(function () { that.manifest.remove(); that.destroyed = true; meows.remove(that.timestamp); if (typeof options.afterDestroy === 'function') { options.afterDestroy.call(null); } if (meows.size() <= 0) { if (default_meow_area instanceof $) { default_meow_area.remove(); default_meow_area = undefined; } if (typeof options.afterDestroyLast === 'function') { options.afterDestroyLast.call(null); } } }); }); } }; }; $.fn.meow = function (args) { var meow = new Meow(args); meows.add(meow); return meow; }; $.meow = $.fn.meow; }; $.fn.meow = function (args) { meows.add(new Meow(args)); }; $.meow = $.fn.meow; }(jQuery, window)); <MSG> Return Meow object upon creation This will allow better control of active meows like programatically disabling them: ` var $alert = $.meow( { title: 'Hello', message: 'Meow' } ); setTimeout( function() {     $alert.destroy(); }, 1000 ); ` <DFF> @@ -191,7 +191,9 @@ }; $.fn.meow = function (args) { - meows.add(new Meow(args)); + var meow = new Meow(args); + meows.add(meow); + return meow; }; $.meow = $.fn.meow; }(jQuery, window));
3
Return Meow object upon creation
1
.js
meow
mit
zacstewart/Meow
10072280
<NME> jquery.meow.js <BEF> (function ($, window) { 'use strict'; // Meow queue var default_meow_area, meows = { queue: {}, add: function (meow) { this.queue[meow.timestamp] = meow; }, get: function (timestamp) { return this.queue[timestamp]; }, remove: function (timestamp) { delete this.queue[timestamp]; }, size: function () { var timestamp, size = 0; for (timestamp in this.queue) { if (this.queue.hasOwnProperty(timestamp)) { size += 1; } } return size; } }, // Meow constructor Meow = function (options) { var that = this; this.timestamp = new Date().getTime(); // used to identify this meow and timeout this.hovered = false; // whether mouse is over or not if (typeof default_meow_area === 'undefined' && typeof options.container === 'undefined') { default_meow_area = $(window.document.createElement('div')) .attr({'id': ((new Date()).getTime()), 'class': 'meows'}); $('body').prepend(default_meow_area); } if (meows.size() <= 0) { if (typeof options.beforeCreateFirst === 'function') { options.beforeCreateFirst.call(that); } } if (typeof options.container === 'string') { this.container = $(options.container); } else { this.container = default_meow_area; } if (typeof options.title === 'string') { this.title = options.title; } if (typeof options.message === 'string') { this.message = options.message; } else if (options.message instanceof $) { if (options.message.is('input,textarea,select')) { this.message = options.message.val(); } else { this.message = options.message.text(); } if (typeof this.title === 'undefined' && typeof options.message.attr('title') === 'string') { this.title = options.message.attr('title'); } } if (typeof options.icon === 'string') { this.icon = options.icon; } if (options.sticky) { this.duration = Infinity; } else { this.duration = options.duration || 5000; } // Call callback if it's defined (this = meow object) if (typeof options.beforeCreate === 'function') { options.beforeCreate.call(that); } // Add the meow to the meow area this.container.append($(window.document.createElement('div')) .attr('id', 'meow-' + this.timestamp.toString()) .addClass('meow') .html($(window.document.createElement('div')).addClass('inner').html(this.message)) .hide() .fadeIn(400)); this.manifest = $('#meow-' + this.timestamp.toString()); // Add title if it's defined if (typeof this.title === 'string') { this.manifest.find('.inner').prepend( $(window.document.createElement('h1')).text(this.title) ); } // Add icon if it's defined if (typeof that.icon === 'string') { this.manifest.find('.inner').prepend( $(window.document.createElement('div')).addClass('icon').html( $(window.document.createElement('img')).attr('src', this.icon) ) ); } // Add close button if the meow isn't uncloseable // TODO: this close button needs to be much prettier if (options.closeable !== false) { this.manifest.find('.inner').prepend( $(window.document.createElement('a')) .addClass('close') .html('&times;') .attr('href', '#close-meow-' + that.timestamp) .click(function (e) { e.preventDefault(); that.destroy(); }) ); } this.manifest.bind('mouseenter mouseleave', function (event) { if (event.type === 'mouseleave') { that.hovered = false; that.manifest.removeClass('hover'); // Destroy the mow on mouseleave if it's timed out if (that.timestamp + that.duration <= new Date().getTime()) { that.destroy(); } } else { that.hovered = true; that.manifest.addClass('hover'); } }); // Add a timeout if the duration isn't Infinity if (this.duration !== Infinity) { this.timeout = window.setTimeout(function () { // Make sure this meow hasn't already been destroyed if (typeof meows.get(that.timestamp) !== 'undefined') { // Call callback if it's defined (this = meow DOM element) if (typeof options.onTimeout === 'function') { options.onTimeout.call(that.manifest); } // Don't destroy if user is hovering over meow if (that.hovered !== true && typeof that === 'object') { that.destroy(); } } }, that.duration); } this.destroy = function () { if (that.destroyed !== true) { // Call callback if it's defined (this = meow DOM element) if (typeof options.beforeDestroy === 'function') { options.beforeDestroy.call(that.manifest); } that.manifest.find('.inner').fadeTo(400, 0, function () { that.manifest.slideUp(function () { that.manifest.remove(); that.destroyed = true; meows.remove(that.timestamp); if (typeof options.afterDestroy === 'function') { options.afterDestroy.call(null); } if (meows.size() <= 0) { if (default_meow_area instanceof $) { default_meow_area.remove(); default_meow_area = undefined; } if (typeof options.afterDestroyLast === 'function') { options.afterDestroyLast.call(null); } } }); }); } }; }; $.fn.meow = function (args) { var meow = new Meow(args); meows.add(meow); return meow; }; $.meow = $.fn.meow; }; $.fn.meow = function (args) { meows.add(new Meow(args)); }; $.meow = $.fn.meow; }(jQuery, window)); <MSG> Return Meow object upon creation This will allow better control of active meows like programatically disabling them: ` var $alert = $.meow( { title: 'Hello', message: 'Meow' } ); setTimeout( function() {     $alert.destroy(); }, 1000 ); ` <DFF> @@ -191,7 +191,9 @@ }; $.fn.meow = function (args) { - meows.add(new Meow(args)); + var meow = new Meow(args); + meows.add(meow); + return meow; }; $.meow = $.fn.meow; }(jQuery, window));
3
Return Meow object upon creation
1
.js
meow
mit
zacstewart/Meow
10072281
<NME> helper.rb <BEF> # frozen_string_literal: true module Split module Helper OVERRIDE_PARAM_NAME = "ab_test" module_function # Check if array is passed to ab_test: ab_test('name', ['Alt 1', 'Alt 2', 'Alt 3']) if control.is_a? Array and alternatives.length.zero? arguments_array = control control, alternatives = control.first, control[1..-1] end raise(Split::InvalidExperimentsFormatError) unless (Split.configuration.experiments || {}).fetch(experiment.name.to_sym, {})[:combined_experiments].nil? trial = Trial.new(user: ab_user, experiment: experiment, override: override_alternative(experiment.name), exclude: exclude_visitor?, disabled: split_generically_disabled?) alt = trial.choose!(self) alt ? alt.name : nil else control_variable(experiment.control) end 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> removing useless line <DFF> @@ -8,7 +8,6 @@ module Split # Check if array is passed to ab_test: ab_test('name', ['Alt 1', 'Alt 2', 'Alt 3']) if control.is_a? Array and alternatives.length.zero? - arguments_array = control control, alternatives = control.first, control[1..-1] end
0
removing useless line
1
.rb
rb
mit
splitrb/split
10072282
<NME> helper.rb <BEF> # frozen_string_literal: true module Split module Helper OVERRIDE_PARAM_NAME = "ab_test" module_function # Check if array is passed to ab_test: ab_test('name', ['Alt 1', 'Alt 2', 'Alt 3']) if control.is_a? Array and alternatives.length.zero? arguments_array = control control, alternatives = control.first, control[1..-1] end raise(Split::InvalidExperimentsFormatError) unless (Split.configuration.experiments || {}).fetch(experiment.name.to_sym, {})[:combined_experiments].nil? trial = Trial.new(user: ab_user, experiment: experiment, override: override_alternative(experiment.name), exclude: exclude_visitor?, disabled: split_generically_disabled?) alt = trial.choose!(self) alt ? alt.name : nil else control_variable(experiment.control) end 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> removing useless line <DFF> @@ -8,7 +8,6 @@ module Split # Check if array is passed to ab_test: ab_test('name', ['Alt 1', 'Alt 2', 'Alt 3']) if control.is_a? Array and alternatives.length.zero? - arguments_array = control control, alternatives = control.first, control[1..-1] end
0
removing useless line
1
.rb
rb
mit
splitrb/split
10072283
<NME> helper.rb <BEF> # frozen_string_literal: true module Split module Helper OVERRIDE_PARAM_NAME = "ab_test" module_function # Check if array is passed to ab_test: ab_test('name', ['Alt 1', 'Alt 2', 'Alt 3']) if control.is_a? Array and alternatives.length.zero? arguments_array = control control, alternatives = control.first, control[1..-1] end raise(Split::InvalidExperimentsFormatError) unless (Split.configuration.experiments || {}).fetch(experiment.name.to_sym, {})[:combined_experiments].nil? trial = Trial.new(user: ab_user, experiment: experiment, override: override_alternative(experiment.name), exclude: exclude_visitor?, disabled: split_generically_disabled?) alt = trial.choose!(self) alt ? alt.name : nil else control_variable(experiment.control) end 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> removing useless line <DFF> @@ -8,7 +8,6 @@ module Split # Check if array is passed to ab_test: ab_test('name', ['Alt 1', 'Alt 2', 'Alt 3']) if control.is_a? Array and alternatives.length.zero? - arguments_array = control control, alternatives = control.first, control[1..-1] end
0
removing useless line
1
.rb
rb
mit
splitrb/split
10072284
<NME> spec_helper.rb <BEF> # frozen_string_literal: true ENV["RACK_ENV"] = "test" require "rubygems" require "bundler/setup" require "simplecov" SimpleCov.start require "split" require "ostruct" require "yaml" def request(ua = 'Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_6_6; de-de) AppleWebKit/533.20.25 (KHTML, like Gecko) Version/5.0.4 Safari/533.20.27') r = OpenStruct.new r.user_agent = ua @request ||= r end before(:each) do Split.configuration = Split::Configuration.new Split.redis = Redis.new Split.redis.select(10) Split.redis.flushdb Split::Cache.clear @ab_user = mock_user @params = nil end end RSpec.configure do |config| config.order = "random" config.include GlobalSharedContext config.raise_errors_for_deprecations! end def session @session ||= {} end def params @params ||= {} end def request(ua = "Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_6_6; de-de) AppleWebKit/533.20.25 (KHTML, like Gecko) Version/5.0.4 Safari/533.20.27") @request ||= begin r = OpenStruct.new r.user_agent = ua r.ip = "192.168.1.1" r end end <MSG> Added ignore_ip_addresses configuration option <DFF> @@ -14,5 +14,6 @@ end def request(ua = 'Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_6_6; de-de) AppleWebKit/533.20.25 (KHTML, like Gecko) Version/5.0.4 Safari/533.20.27') r = OpenStruct.new r.user_agent = ua + r.ip = '192.168.1.1' @request ||= r end \ No newline at end of file
1
Added ignore_ip_addresses configuration option
0
.rb
rb
mit
splitrb/split
10072285
<NME> spec_helper.rb <BEF> # frozen_string_literal: true ENV["RACK_ENV"] = "test" require "rubygems" require "bundler/setup" require "simplecov" SimpleCov.start require "split" require "ostruct" require "yaml" def request(ua = 'Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_6_6; de-de) AppleWebKit/533.20.25 (KHTML, like Gecko) Version/5.0.4 Safari/533.20.27') r = OpenStruct.new r.user_agent = ua @request ||= r end before(:each) do Split.configuration = Split::Configuration.new Split.redis = Redis.new Split.redis.select(10) Split.redis.flushdb Split::Cache.clear @ab_user = mock_user @params = nil end end RSpec.configure do |config| config.order = "random" config.include GlobalSharedContext config.raise_errors_for_deprecations! end def session @session ||= {} end def params @params ||= {} end def request(ua = "Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_6_6; de-de) AppleWebKit/533.20.25 (KHTML, like Gecko) Version/5.0.4 Safari/533.20.27") @request ||= begin r = OpenStruct.new r.user_agent = ua r.ip = "192.168.1.1" r end end <MSG> Added ignore_ip_addresses configuration option <DFF> @@ -14,5 +14,6 @@ end def request(ua = 'Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_6_6; de-de) AppleWebKit/533.20.25 (KHTML, like Gecko) Version/5.0.4 Safari/533.20.27') r = OpenStruct.new r.user_agent = ua + r.ip = '192.168.1.1' @request ||= r end \ No newline at end of file
1
Added ignore_ip_addresses configuration option
0
.rb
rb
mit
splitrb/split
10072286
<NME> spec_helper.rb <BEF> # frozen_string_literal: true ENV["RACK_ENV"] = "test" require "rubygems" require "bundler/setup" require "simplecov" SimpleCov.start require "split" require "ostruct" require "yaml" def request(ua = 'Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_6_6; de-de) AppleWebKit/533.20.25 (KHTML, like Gecko) Version/5.0.4 Safari/533.20.27') r = OpenStruct.new r.user_agent = ua @request ||= r end before(:each) do Split.configuration = Split::Configuration.new Split.redis = Redis.new Split.redis.select(10) Split.redis.flushdb Split::Cache.clear @ab_user = mock_user @params = nil end end RSpec.configure do |config| config.order = "random" config.include GlobalSharedContext config.raise_errors_for_deprecations! end def session @session ||= {} end def params @params ||= {} end def request(ua = "Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_6_6; de-de) AppleWebKit/533.20.25 (KHTML, like Gecko) Version/5.0.4 Safari/533.20.27") @request ||= begin r = OpenStruct.new r.user_agent = ua r.ip = "192.168.1.1" r end end <MSG> Added ignore_ip_addresses configuration option <DFF> @@ -14,5 +14,6 @@ end def request(ua = 'Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_6_6; de-de) AppleWebKit/533.20.25 (KHTML, like Gecko) Version/5.0.4 Safari/533.20.27') r = OpenStruct.new r.user_agent = ua + r.ip = '192.168.1.1' @request ||= r end \ No newline at end of file
1
Added ignore_ip_addresses configuration option
0
.rb
rb
mit
splitrb/split
10072287
<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" finished :my_metric, :reset => false ab_user.should eql(@experiment.key => @alternative_name, @experiment.finished_key => true) end end end 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 "pulls options from config file" do Split.configuration.experiments[:my_experiment] = { :alternatives => [ "control_opt", "other_opt" ], } ab_test :my_experiment Split::Experiment.find(:my_experiment).alternative_names.should == [ "control_opt", "other_opt" ] end it "can be called multiple times" do Split.configuration.experiments[:my_experiment] = { :alternatives => [ "control_opt", "other_opt" ], } 5.times { ab_test :my_experiment } experiment = Split::Experiment.find(:my_experiment) experiment.alternative_names.should == [ "control_opt", "other_opt" ] experiment.participant_count.should == 1 end it "accepts multiple alternatives" do Split.configuration.experiments[:my_experiment] = { :alternatives => [ "control_opt", "second_opt", "third_opt" ], 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") it "should increment the counter for the specified-goal completed alternative" do @previous_completion_count_for_goal1 = Split::Alternative.new(@alternative_name, @experiment_name).completed_count(@goal1) @previous_completion_count_for_goal2 = Split::Alternative.new(@alternative_name, @experiment_name).completed_count(@goal2) finished(@experiment) new_completion_count_for_goal1 = Split::Alternative.new(@alternative_name, @experiment_name).completed_count(@goal1) new_completion_count_for_goal1.should eql(@previous_completion_count_for_goal1 + 1) new_completion_count_for_goal2 = Split::Alternative.new(@alternative_name, @experiment_name).completed_count(@goal2) new_completion_count_for_goal2.should eql(@previous_completion_count_for_goal2 + 1) end end end @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> fix some bugs <DFF> @@ -264,6 +264,7 @@ describe Split::Helper do finished :my_metric, :reset => false ab_user.should eql(@experiment.key => @alternative_name, @experiment.finished_key => true) end + end end @@ -575,21 +576,43 @@ describe Split::Helper do it "pulls options from config file" do Split.configuration.experiments[:my_experiment] = { :alternatives => [ "control_opt", "other_opt" ], + :goals => ["goal1", "goal2"] } ab_test :my_experiment Split::Experiment.find(:my_experiment).alternative_names.should == [ "control_opt", "other_opt" ] + Split::Experiment.find(:my_experiment).goals.should == [ "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.find(:my_experiment) experiment.alternative_names.should == [ "control_opt", "other_opt" ] + experiment.goals.should == [ "goal1", "goal2" ] experiment.participant_count.should == 1 end + it "accepts multiple goals" do + Split.configuration.experiments[:my_experiment] = { + :variants => [ "control_opt", "other_opt" ], + :goals => [ "goal1", "goal2", "goal3" ] + } + ab_test :my_experiment + experiment = Split::Experiment.find(:my_experiment) + experiment.goals.should == [ "goal1", "goal2", "goal3" ] + end + + 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 == [] + end + it "accepts multiple alternatives" do Split.configuration.experiments[:my_experiment] = { :alternatives => [ "control_opt", "second_opt", "third_opt" ], @@ -701,11 +724,11 @@ describe Split::Helper do it "should increment the counter for the specified-goal completed alternative" do @previous_completion_count_for_goal1 = Split::Alternative.new(@alternative_name, @experiment_name).completed_count(@goal1) @previous_completion_count_for_goal2 = Split::Alternative.new(@alternative_name, @experiment_name).completed_count(@goal2) - finished(@experiment) + finished({"link_color" => ["purchase"]}) new_completion_count_for_goal1 = Split::Alternative.new(@alternative_name, @experiment_name).completed_count(@goal1) new_completion_count_for_goal1.should eql(@previous_completion_count_for_goal1 + 1) new_completion_count_for_goal2 = Split::Alternative.new(@alternative_name, @experiment_name).completed_count(@goal2) - new_completion_count_for_goal2.should eql(@previous_completion_count_for_goal2 + 1) + new_completion_count_for_goal2.should eql(@previous_completion_count_for_goal2) end end end
25
fix some bugs
2
.rb
rb
mit
splitrb/split
10072288
<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" finished :my_metric, :reset => false ab_user.should eql(@experiment.key => @alternative_name, @experiment.finished_key => true) end end end 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 "pulls options from config file" do Split.configuration.experiments[:my_experiment] = { :alternatives => [ "control_opt", "other_opt" ], } ab_test :my_experiment Split::Experiment.find(:my_experiment).alternative_names.should == [ "control_opt", "other_opt" ] end it "can be called multiple times" do Split.configuration.experiments[:my_experiment] = { :alternatives => [ "control_opt", "other_opt" ], } 5.times { ab_test :my_experiment } experiment = Split::Experiment.find(:my_experiment) experiment.alternative_names.should == [ "control_opt", "other_opt" ] experiment.participant_count.should == 1 end it "accepts multiple alternatives" do Split.configuration.experiments[:my_experiment] = { :alternatives => [ "control_opt", "second_opt", "third_opt" ], 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") it "should increment the counter for the specified-goal completed alternative" do @previous_completion_count_for_goal1 = Split::Alternative.new(@alternative_name, @experiment_name).completed_count(@goal1) @previous_completion_count_for_goal2 = Split::Alternative.new(@alternative_name, @experiment_name).completed_count(@goal2) finished(@experiment) new_completion_count_for_goal1 = Split::Alternative.new(@alternative_name, @experiment_name).completed_count(@goal1) new_completion_count_for_goal1.should eql(@previous_completion_count_for_goal1 + 1) new_completion_count_for_goal2 = Split::Alternative.new(@alternative_name, @experiment_name).completed_count(@goal2) new_completion_count_for_goal2.should eql(@previous_completion_count_for_goal2 + 1) end end end @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> fix some bugs <DFF> @@ -264,6 +264,7 @@ describe Split::Helper do finished :my_metric, :reset => false ab_user.should eql(@experiment.key => @alternative_name, @experiment.finished_key => true) end + end end @@ -575,21 +576,43 @@ describe Split::Helper do it "pulls options from config file" do Split.configuration.experiments[:my_experiment] = { :alternatives => [ "control_opt", "other_opt" ], + :goals => ["goal1", "goal2"] } ab_test :my_experiment Split::Experiment.find(:my_experiment).alternative_names.should == [ "control_opt", "other_opt" ] + Split::Experiment.find(:my_experiment).goals.should == [ "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.find(:my_experiment) experiment.alternative_names.should == [ "control_opt", "other_opt" ] + experiment.goals.should == [ "goal1", "goal2" ] experiment.participant_count.should == 1 end + it "accepts multiple goals" do + Split.configuration.experiments[:my_experiment] = { + :variants => [ "control_opt", "other_opt" ], + :goals => [ "goal1", "goal2", "goal3" ] + } + ab_test :my_experiment + experiment = Split::Experiment.find(:my_experiment) + experiment.goals.should == [ "goal1", "goal2", "goal3" ] + end + + 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 == [] + end + it "accepts multiple alternatives" do Split.configuration.experiments[:my_experiment] = { :alternatives => [ "control_opt", "second_opt", "third_opt" ], @@ -701,11 +724,11 @@ describe Split::Helper do it "should increment the counter for the specified-goal completed alternative" do @previous_completion_count_for_goal1 = Split::Alternative.new(@alternative_name, @experiment_name).completed_count(@goal1) @previous_completion_count_for_goal2 = Split::Alternative.new(@alternative_name, @experiment_name).completed_count(@goal2) - finished(@experiment) + finished({"link_color" => ["purchase"]}) new_completion_count_for_goal1 = Split::Alternative.new(@alternative_name, @experiment_name).completed_count(@goal1) new_completion_count_for_goal1.should eql(@previous_completion_count_for_goal1 + 1) new_completion_count_for_goal2 = Split::Alternative.new(@alternative_name, @experiment_name).completed_count(@goal2) - new_completion_count_for_goal2.should eql(@previous_completion_count_for_goal2 + 1) + new_completion_count_for_goal2.should eql(@previous_completion_count_for_goal2) end end end
25
fix some bugs
2
.rb
rb
mit
splitrb/split
10072289
<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" finished :my_metric, :reset => false ab_user.should eql(@experiment.key => @alternative_name, @experiment.finished_key => true) end end end 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 "pulls options from config file" do Split.configuration.experiments[:my_experiment] = { :alternatives => [ "control_opt", "other_opt" ], } ab_test :my_experiment Split::Experiment.find(:my_experiment).alternative_names.should == [ "control_opt", "other_opt" ] end it "can be called multiple times" do Split.configuration.experiments[:my_experiment] = { :alternatives => [ "control_opt", "other_opt" ], } 5.times { ab_test :my_experiment } experiment = Split::Experiment.find(:my_experiment) experiment.alternative_names.should == [ "control_opt", "other_opt" ] experiment.participant_count.should == 1 end it "accepts multiple alternatives" do Split.configuration.experiments[:my_experiment] = { :alternatives => [ "control_opt", "second_opt", "third_opt" ], 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") it "should increment the counter for the specified-goal completed alternative" do @previous_completion_count_for_goal1 = Split::Alternative.new(@alternative_name, @experiment_name).completed_count(@goal1) @previous_completion_count_for_goal2 = Split::Alternative.new(@alternative_name, @experiment_name).completed_count(@goal2) finished(@experiment) new_completion_count_for_goal1 = Split::Alternative.new(@alternative_name, @experiment_name).completed_count(@goal1) new_completion_count_for_goal1.should eql(@previous_completion_count_for_goal1 + 1) new_completion_count_for_goal2 = Split::Alternative.new(@alternative_name, @experiment_name).completed_count(@goal2) new_completion_count_for_goal2.should eql(@previous_completion_count_for_goal2 + 1) end end end @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> fix some bugs <DFF> @@ -264,6 +264,7 @@ describe Split::Helper do finished :my_metric, :reset => false ab_user.should eql(@experiment.key => @alternative_name, @experiment.finished_key => true) end + end end @@ -575,21 +576,43 @@ describe Split::Helper do it "pulls options from config file" do Split.configuration.experiments[:my_experiment] = { :alternatives => [ "control_opt", "other_opt" ], + :goals => ["goal1", "goal2"] } ab_test :my_experiment Split::Experiment.find(:my_experiment).alternative_names.should == [ "control_opt", "other_opt" ] + Split::Experiment.find(:my_experiment).goals.should == [ "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.find(:my_experiment) experiment.alternative_names.should == [ "control_opt", "other_opt" ] + experiment.goals.should == [ "goal1", "goal2" ] experiment.participant_count.should == 1 end + it "accepts multiple goals" do + Split.configuration.experiments[:my_experiment] = { + :variants => [ "control_opt", "other_opt" ], + :goals => [ "goal1", "goal2", "goal3" ] + } + ab_test :my_experiment + experiment = Split::Experiment.find(:my_experiment) + experiment.goals.should == [ "goal1", "goal2", "goal3" ] + end + + 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 == [] + end + it "accepts multiple alternatives" do Split.configuration.experiments[:my_experiment] = { :alternatives => [ "control_opt", "second_opt", "third_opt" ], @@ -701,11 +724,11 @@ describe Split::Helper do it "should increment the counter for the specified-goal completed alternative" do @previous_completion_count_for_goal1 = Split::Alternative.new(@alternative_name, @experiment_name).completed_count(@goal1) @previous_completion_count_for_goal2 = Split::Alternative.new(@alternative_name, @experiment_name).completed_count(@goal2) - finished(@experiment) + finished({"link_color" => ["purchase"]}) new_completion_count_for_goal1 = Split::Alternative.new(@alternative_name, @experiment_name).completed_count(@goal1) new_completion_count_for_goal1.should eql(@previous_completion_count_for_goal1 + 1) new_completion_count_for_goal2 = Split::Alternative.new(@alternative_name, @experiment_name).completed_count(@goal2) - new_completion_count_for_goal2.should eql(@previous_completion_count_for_goal2 + 1) + new_completion_count_for_goal2.should eql(@previous_completion_count_for_goal2) end end end
25
fix some bugs
2
.rb
rb
mit
splitrb/split
10072290
<NME> redis_adapter_spec.rb <BEF> # frozen_string_literal: true require "spec_helper" describe Split::Persistence::RedisAdapter do subject { Split::Persistence::RedisAdapter.new(context) } describe "#[] and #[]=" do it "should set and return the value for given key" do subject["my_key"] = "my_value" let(:context) { double(method_name: "val") } it 'should be "persistence:bar"' do expect(subject.redis_key).to eq("persistence:val") end end context "config with namespace and lookup_by" do before { Split::Persistence::RedisAdapter.with_config(lookup_by: proc { "frag" }, namespace: "namer") } it 'should be "namer"' do expect(subject.redis_key).to eq("namer:frag") end end end describe "#find" do before { Split::Persistence::RedisAdapter.with_config(lookup_by: proc { "frag" }, namespace: "a_namespace") } it "should create and user from a given key" do adapter = Split::Persistence::RedisAdapter.find(2) expect(adapter.redis_key).to eq("a_namespace:2") end end context "functional tests" do before { Split::Persistence::RedisAdapter.with_config(lookup_by: "lookup") } describe "#[] and #[]=" do it "should set and return the value for given key" do subject["my_key"] = "my_value" expect(subject["my_key"]).to eq("my_value") end end describe "#delete" do it "should delete the given key" do subject["my_key"] = "my_value" subject.delete("my_key") expect(subject["my_key"]).to be_nil end end describe "#keys" do it "should return an array of the user's stored keys" do subject["my_key"] = "my_value" subject["my_second_key"] = "my_second_value" expect(subject.keys).to match(["my_key", "my_second_key"]) end end end end <MSG> Added configuration to RedisAdapter <DFF> @@ -6,6 +6,41 @@ describe Split::Persistence::RedisAdapter do subject { Split::Persistence::RedisAdapter.new(context) } + describe '#redis_key' do + before { Split::Persistence::RedisAdapter.reset_config! } + + context 'default' do + it 'should be "persistence"' do + subject.redis_key.should == 'persistence' + end + end + + context 'config with namespace' do + before { Split::Persistence::RedisAdapter.with_config(:namespace => 'namer') } + + it 'should be "namer"' do + subject.redis_key.should == 'namer' + end + end + + context 'config with lookup_by = "method_name"' do + before { Split::Persistence::RedisAdapter.with_config(:lookup_by => 'method_name') } + let(:context) { double(:method_name => 'val') } + + it 'should be "persistence:bar"' do + subject.redis_key.should == 'persistence:val' + end + end + + context 'config with lookup_by = proc { "block" }' do + before { Split::Persistence::RedisAdapter.with_config(:lookup_by => proc{'block'}) } + + it 'should be "persistence:block"' do + subject.redis_key.should == 'persistence:block' + end + end + end + describe "#[] and #[]=" do it "should set and return the value for given key" do subject["my_key"] = "my_value"
35
Added configuration to RedisAdapter
0
.rb
rb
mit
splitrb/split
10072291
<NME> redis_adapter_spec.rb <BEF> # frozen_string_literal: true require "spec_helper" describe Split::Persistence::RedisAdapter do subject { Split::Persistence::RedisAdapter.new(context) } describe "#[] and #[]=" do it "should set and return the value for given key" do subject["my_key"] = "my_value" let(:context) { double(method_name: "val") } it 'should be "persistence:bar"' do expect(subject.redis_key).to eq("persistence:val") end end context "config with namespace and lookup_by" do before { Split::Persistence::RedisAdapter.with_config(lookup_by: proc { "frag" }, namespace: "namer") } it 'should be "namer"' do expect(subject.redis_key).to eq("namer:frag") end end end describe "#find" do before { Split::Persistence::RedisAdapter.with_config(lookup_by: proc { "frag" }, namespace: "a_namespace") } it "should create and user from a given key" do adapter = Split::Persistence::RedisAdapter.find(2) expect(adapter.redis_key).to eq("a_namespace:2") end end context "functional tests" do before { Split::Persistence::RedisAdapter.with_config(lookup_by: "lookup") } describe "#[] and #[]=" do it "should set and return the value for given key" do subject["my_key"] = "my_value" expect(subject["my_key"]).to eq("my_value") end end describe "#delete" do it "should delete the given key" do subject["my_key"] = "my_value" subject.delete("my_key") expect(subject["my_key"]).to be_nil end end describe "#keys" do it "should return an array of the user's stored keys" do subject["my_key"] = "my_value" subject["my_second_key"] = "my_second_value" expect(subject.keys).to match(["my_key", "my_second_key"]) end end end end <MSG> Added configuration to RedisAdapter <DFF> @@ -6,6 +6,41 @@ describe Split::Persistence::RedisAdapter do subject { Split::Persistence::RedisAdapter.new(context) } + describe '#redis_key' do + before { Split::Persistence::RedisAdapter.reset_config! } + + context 'default' do + it 'should be "persistence"' do + subject.redis_key.should == 'persistence' + end + end + + context 'config with namespace' do + before { Split::Persistence::RedisAdapter.with_config(:namespace => 'namer') } + + it 'should be "namer"' do + subject.redis_key.should == 'namer' + end + end + + context 'config with lookup_by = "method_name"' do + before { Split::Persistence::RedisAdapter.with_config(:lookup_by => 'method_name') } + let(:context) { double(:method_name => 'val') } + + it 'should be "persistence:bar"' do + subject.redis_key.should == 'persistence:val' + end + end + + context 'config with lookup_by = proc { "block" }' do + before { Split::Persistence::RedisAdapter.with_config(:lookup_by => proc{'block'}) } + + it 'should be "persistence:block"' do + subject.redis_key.should == 'persistence:block' + end + end + end + describe "#[] and #[]=" do it "should set and return the value for given key" do subject["my_key"] = "my_value"
35
Added configuration to RedisAdapter
0
.rb
rb
mit
splitrb/split
10072292
<NME> redis_adapter_spec.rb <BEF> # frozen_string_literal: true require "spec_helper" describe Split::Persistence::RedisAdapter do subject { Split::Persistence::RedisAdapter.new(context) } describe "#[] and #[]=" do it "should set and return the value for given key" do subject["my_key"] = "my_value" let(:context) { double(method_name: "val") } it 'should be "persistence:bar"' do expect(subject.redis_key).to eq("persistence:val") end end context "config with namespace and lookup_by" do before { Split::Persistence::RedisAdapter.with_config(lookup_by: proc { "frag" }, namespace: "namer") } it 'should be "namer"' do expect(subject.redis_key).to eq("namer:frag") end end end describe "#find" do before { Split::Persistence::RedisAdapter.with_config(lookup_by: proc { "frag" }, namespace: "a_namespace") } it "should create and user from a given key" do adapter = Split::Persistence::RedisAdapter.find(2) expect(adapter.redis_key).to eq("a_namespace:2") end end context "functional tests" do before { Split::Persistence::RedisAdapter.with_config(lookup_by: "lookup") } describe "#[] and #[]=" do it "should set and return the value for given key" do subject["my_key"] = "my_value" expect(subject["my_key"]).to eq("my_value") end end describe "#delete" do it "should delete the given key" do subject["my_key"] = "my_value" subject.delete("my_key") expect(subject["my_key"]).to be_nil end end describe "#keys" do it "should return an array of the user's stored keys" do subject["my_key"] = "my_value" subject["my_second_key"] = "my_second_value" expect(subject.keys).to match(["my_key", "my_second_key"]) end end end end <MSG> Added configuration to RedisAdapter <DFF> @@ -6,6 +6,41 @@ describe Split::Persistence::RedisAdapter do subject { Split::Persistence::RedisAdapter.new(context) } + describe '#redis_key' do + before { Split::Persistence::RedisAdapter.reset_config! } + + context 'default' do + it 'should be "persistence"' do + subject.redis_key.should == 'persistence' + end + end + + context 'config with namespace' do + before { Split::Persistence::RedisAdapter.with_config(:namespace => 'namer') } + + it 'should be "namer"' do + subject.redis_key.should == 'namer' + end + end + + context 'config with lookup_by = "method_name"' do + before { Split::Persistence::RedisAdapter.with_config(:lookup_by => 'method_name') } + let(:context) { double(:method_name => 'val') } + + it 'should be "persistence:bar"' do + subject.redis_key.should == 'persistence:val' + end + end + + context 'config with lookup_by = proc { "block" }' do + before { Split::Persistence::RedisAdapter.with_config(:lookup_by => proc{'block'}) } + + it 'should be "persistence:block"' do + subject.redis_key.should == 'persistence:block' + end + end + end + describe "#[] and #[]=" do it "should set and return the value for given key" do subject["my_key"] = "my_value"
35
Added configuration to RedisAdapter
0
.rb
rb
mit
splitrb/split
10072293
<NME> LICENSE <BEF> MIT License Copyright (c) 2017 Emmet.io Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. <MSG> Prepare for release <DFF> @@ -1,6 +1,6 @@ MIT License -Copyright (c) 2017 Emmet.io +Copyright (c) 2020 Sergey Chikuyonok <serge.che@gmail.com> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal
1
Prepare for release
1
LICENSE
mit
emmetio/emmet
10072294
<NME> LICENSE <BEF> MIT License Copyright (c) 2017 Emmet.io Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. <MSG> Prepare for release <DFF> @@ -1,6 +1,6 @@ MIT License -Copyright (c) 2017 Emmet.io +Copyright (c) 2020 Sergey Chikuyonok <serge.che@gmail.com> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal
1
Prepare for release
1
LICENSE
mit
emmetio/emmet
10072295
<NME> karma.conf.js <BEF> ADDFILE <MSG> chore(karma.conf.js): Added basic karma.conf.js file <DFF> @@ -0,0 +1,66 @@ +module.exports = function(config) { + config.set({ + + // base path that will be used to resolve all patterns (eg. files, exclude) + basePath: '', + + + // frameworks to use + // available frameworks: https://npmjs.org/browse/keyword/karma-adapter + frameworks: ['jasmine'], + + + // list of files / patterns to load in the browser + files: [ + 'lib/jquery/dist/jquery.js', + 'lib/semantic-ui/dist/semantic.js', + 'lib/angular/angular.js', + 'src/**/*.js', + 'src/**/*.spec.js' + ], + + + // list of files to exclude + exclude: [ + ], + + + // preprocess matching files before serving them to the browser + // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor + preprocessors: { + }, + + + // test results reporter to use + // possible values: 'dots', 'progress' + // available reporters: https://npmjs.org/browse/keyword/karma-reporter + reporters: ['progress'], + + + // web server port + port: 9876, + + + // enable / disable colors in the output (reporters and logs) + colors: true, + + + // level of logging + // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG + logLevel: config.LOG_INFO, + + + // enable / disable watching file and executing tests whenever any file changes + autoWatch: false, + + + // start these browsers + // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher + browsers: ['PhantomJS'], + + + // Continuous Integration mode + // if true, Karma captures browsers, runs the tests and exits + singleRun: false + }); +};
66
chore(karma.conf.js): Added basic karma.conf.js file
0
.js
conf
mit
Semantic-Org/Semantic-UI-Angular
10072296
<NME> karma.conf.js <BEF> ADDFILE <MSG> chore(karma.conf.js): Added basic karma.conf.js file <DFF> @@ -0,0 +1,66 @@ +module.exports = function(config) { + config.set({ + + // base path that will be used to resolve all patterns (eg. files, exclude) + basePath: '', + + + // frameworks to use + // available frameworks: https://npmjs.org/browse/keyword/karma-adapter + frameworks: ['jasmine'], + + + // list of files / patterns to load in the browser + files: [ + 'lib/jquery/dist/jquery.js', + 'lib/semantic-ui/dist/semantic.js', + 'lib/angular/angular.js', + 'src/**/*.js', + 'src/**/*.spec.js' + ], + + + // list of files to exclude + exclude: [ + ], + + + // preprocess matching files before serving them to the browser + // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor + preprocessors: { + }, + + + // test results reporter to use + // possible values: 'dots', 'progress' + // available reporters: https://npmjs.org/browse/keyword/karma-reporter + reporters: ['progress'], + + + // web server port + port: 9876, + + + // enable / disable colors in the output (reporters and logs) + colors: true, + + + // level of logging + // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG + logLevel: config.LOG_INFO, + + + // enable / disable watching file and executing tests whenever any file changes + autoWatch: false, + + + // start these browsers + // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher + browsers: ['PhantomJS'], + + + // Continuous Integration mode + // if true, Karma captures browsers, runs the tests and exits + singleRun: false + }); +};
66
chore(karma.conf.js): Added basic karma.conf.js file
0
.js
conf
mit
Semantic-Org/Semantic-UI-Angular
10072297
<NME> karma.conf.js <BEF> ADDFILE <MSG> chore(karma.conf.js): Added basic karma.conf.js file <DFF> @@ -0,0 +1,66 @@ +module.exports = function(config) { + config.set({ + + // base path that will be used to resolve all patterns (eg. files, exclude) + basePath: '', + + + // frameworks to use + // available frameworks: https://npmjs.org/browse/keyword/karma-adapter + frameworks: ['jasmine'], + + + // list of files / patterns to load in the browser + files: [ + 'lib/jquery/dist/jquery.js', + 'lib/semantic-ui/dist/semantic.js', + 'lib/angular/angular.js', + 'src/**/*.js', + 'src/**/*.spec.js' + ], + + + // list of files to exclude + exclude: [ + ], + + + // preprocess matching files before serving them to the browser + // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor + preprocessors: { + }, + + + // test results reporter to use + // possible values: 'dots', 'progress' + // available reporters: https://npmjs.org/browse/keyword/karma-reporter + reporters: ['progress'], + + + // web server port + port: 9876, + + + // enable / disable colors in the output (reporters and logs) + colors: true, + + + // level of logging + // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG + logLevel: config.LOG_INFO, + + + // enable / disable watching file and executing tests whenever any file changes + autoWatch: false, + + + // start these browsers + // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher + browsers: ['PhantomJS'], + + + // Continuous Integration mode + // if true, Karma captures browsers, runs the tests and exits + singleRun: false + }); +};
66
chore(karma.conf.js): Added basic karma.conf.js file
0
.js
conf
mit
Semantic-Org/Semantic-UI-Angular
10072298
<NME> trial_spec.rb <BEF> # frozen_string_literal: true require "spec_helper" describe Split::Trial do it "should be initializeable" do experiment = mock('experiment') alternative = mock('alternative') trial = Split::Trial.new(:experiment => experiment, :alternative => alternative) trial.experiment.should == experiment trial.alternative.should == alternative end describe "alternative" do it "should use the alternative if specified" do trial = Split::Trial.new(:experiment => experiment = mock('experiment'), :alternative => alternative = mock('alternative')) trial.should_not_receive(:choose) trial.alternative.should == 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 it "should choose from the available alternatives" do trial = Split::Trial.new(:experiment => experiment = mock('experiment')) experiment.should_receive(:next_alternative).and_return(alternative = mock('alternative')) alternative.should_receive(:increment_participation) experiment.stub(:winner).and_return nil trial.choose! 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! experiment = Split::Experiment.new('basket_text', :alternatives => ['basket', "cart"]) experiment.save trial = Split::Trial.new(:experiment => experiment, :alternative_name => 'basket') trial.alternative.name.should == 'basket' end end 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 pull request #125 from iangreenleaf/refactor_trial Collapse :alternative_name and :alternative options in Trial <DFF> @@ -4,7 +4,7 @@ require 'split/trial' describe Split::Trial do it "should be initializeable" do experiment = mock('experiment') - alternative = mock('alternative') + alternative = mock('alternative', :kind_of? => Split::Alternative) trial = Split::Trial.new(:experiment => experiment, :alternative => alternative) trial.experiment.should == experiment trial.alternative.should == alternative @@ -12,7 +12,8 @@ describe Split::Trial do describe "alternative" do it "should use the alternative if specified" do - trial = Split::Trial.new(:experiment => experiment = mock('experiment'), :alternative => alternative = mock('alternative')) + alternative = mock('alternative', :kind_of? => Split::Alternative) + trial = Split::Trial.new(:experiment => experiment = mock('experiment'), :alternative => alternative) trial.should_not_receive(:choose) trial.alternative.should == alternative end @@ -38,7 +39,8 @@ describe Split::Trial do it "should choose from the available alternatives" do trial = Split::Trial.new(:experiment => experiment = mock('experiment')) - experiment.should_receive(:next_alternative).and_return(alternative = mock('alternative')) + alternative = mock('alternative', :kind_of? => Split::Alternative) + experiment.should_receive(:next_alternative).and_return(alternative) alternative.should_receive(:increment_participation) experiment.stub(:winner).and_return nil trial.choose! @@ -52,7 +54,7 @@ describe Split::Trial do experiment = Split::Experiment.new('basket_text', :alternatives => ['basket', "cart"]) experiment.save - trial = Split::Trial.new(:experiment => experiment, :alternative_name => 'basket') + trial = Split::Trial.new(:experiment => experiment, :alternative => 'basket') trial.alternative.name.should == 'basket' end end
6
Merge pull request #125 from iangreenleaf/refactor_trial
4
.rb
rb
mit
splitrb/split
10072299
<NME> trial_spec.rb <BEF> # frozen_string_literal: true require "spec_helper" describe Split::Trial do it "should be initializeable" do experiment = mock('experiment') alternative = mock('alternative') trial = Split::Trial.new(:experiment => experiment, :alternative => alternative) trial.experiment.should == experiment trial.alternative.should == alternative end describe "alternative" do it "should use the alternative if specified" do trial = Split::Trial.new(:experiment => experiment = mock('experiment'), :alternative => alternative = mock('alternative')) trial.should_not_receive(:choose) trial.alternative.should == 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 it "should choose from the available alternatives" do trial = Split::Trial.new(:experiment => experiment = mock('experiment')) experiment.should_receive(:next_alternative).and_return(alternative = mock('alternative')) alternative.should_receive(:increment_participation) experiment.stub(:winner).and_return nil trial.choose! 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! experiment = Split::Experiment.new('basket_text', :alternatives => ['basket', "cart"]) experiment.save trial = Split::Trial.new(:experiment => experiment, :alternative_name => 'basket') trial.alternative.name.should == 'basket' end end 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 pull request #125 from iangreenleaf/refactor_trial Collapse :alternative_name and :alternative options in Trial <DFF> @@ -4,7 +4,7 @@ require 'split/trial' describe Split::Trial do it "should be initializeable" do experiment = mock('experiment') - alternative = mock('alternative') + alternative = mock('alternative', :kind_of? => Split::Alternative) trial = Split::Trial.new(:experiment => experiment, :alternative => alternative) trial.experiment.should == experiment trial.alternative.should == alternative @@ -12,7 +12,8 @@ describe Split::Trial do describe "alternative" do it "should use the alternative if specified" do - trial = Split::Trial.new(:experiment => experiment = mock('experiment'), :alternative => alternative = mock('alternative')) + alternative = mock('alternative', :kind_of? => Split::Alternative) + trial = Split::Trial.new(:experiment => experiment = mock('experiment'), :alternative => alternative) trial.should_not_receive(:choose) trial.alternative.should == alternative end @@ -38,7 +39,8 @@ describe Split::Trial do it "should choose from the available alternatives" do trial = Split::Trial.new(:experiment => experiment = mock('experiment')) - experiment.should_receive(:next_alternative).and_return(alternative = mock('alternative')) + alternative = mock('alternative', :kind_of? => Split::Alternative) + experiment.should_receive(:next_alternative).and_return(alternative) alternative.should_receive(:increment_participation) experiment.stub(:winner).and_return nil trial.choose! @@ -52,7 +54,7 @@ describe Split::Trial do experiment = Split::Experiment.new('basket_text', :alternatives => ['basket', "cart"]) experiment.save - trial = Split::Trial.new(:experiment => experiment, :alternative_name => 'basket') + trial = Split::Trial.new(:experiment => experiment, :alternative => 'basket') trial.alternative.name.should == 'basket' end end
6
Merge pull request #125 from iangreenleaf/refactor_trial
4
.rb
rb
mit
splitrb/split
10072300
<NME> trial_spec.rb <BEF> # frozen_string_literal: true require "spec_helper" describe Split::Trial do it "should be initializeable" do experiment = mock('experiment') alternative = mock('alternative') trial = Split::Trial.new(:experiment => experiment, :alternative => alternative) trial.experiment.should == experiment trial.alternative.should == alternative end describe "alternative" do it "should use the alternative if specified" do trial = Split::Trial.new(:experiment => experiment = mock('experiment'), :alternative => alternative = mock('alternative')) trial.should_not_receive(:choose) trial.alternative.should == 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 it "should choose from the available alternatives" do trial = Split::Trial.new(:experiment => experiment = mock('experiment')) experiment.should_receive(:next_alternative).and_return(alternative = mock('alternative')) alternative.should_receive(:increment_participation) experiment.stub(:winner).and_return nil trial.choose! 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! experiment = Split::Experiment.new('basket_text', :alternatives => ['basket', "cart"]) experiment.save trial = Split::Trial.new(:experiment => experiment, :alternative_name => 'basket') trial.alternative.name.should == 'basket' end end 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 pull request #125 from iangreenleaf/refactor_trial Collapse :alternative_name and :alternative options in Trial <DFF> @@ -4,7 +4,7 @@ require 'split/trial' describe Split::Trial do it "should be initializeable" do experiment = mock('experiment') - alternative = mock('alternative') + alternative = mock('alternative', :kind_of? => Split::Alternative) trial = Split::Trial.new(:experiment => experiment, :alternative => alternative) trial.experiment.should == experiment trial.alternative.should == alternative @@ -12,7 +12,8 @@ describe Split::Trial do describe "alternative" do it "should use the alternative if specified" do - trial = Split::Trial.new(:experiment => experiment = mock('experiment'), :alternative => alternative = mock('alternative')) + alternative = mock('alternative', :kind_of? => Split::Alternative) + trial = Split::Trial.new(:experiment => experiment = mock('experiment'), :alternative => alternative) trial.should_not_receive(:choose) trial.alternative.should == alternative end @@ -38,7 +39,8 @@ describe Split::Trial do it "should choose from the available alternatives" do trial = Split::Trial.new(:experiment => experiment = mock('experiment')) - experiment.should_receive(:next_alternative).and_return(alternative = mock('alternative')) + alternative = mock('alternative', :kind_of? => Split::Alternative) + experiment.should_receive(:next_alternative).and_return(alternative) alternative.should_receive(:increment_participation) experiment.stub(:winner).and_return nil trial.choose! @@ -52,7 +54,7 @@ describe Split::Trial do experiment = Split::Experiment.new('basket_text', :alternatives => ['basket', "cart"]) experiment.save - trial = Split::Trial.new(:experiment => experiment, :alternative_name => 'basket') + trial = Split::Trial.new(:experiment => experiment, :alternative => 'basket') trial.alternative.name.should == 'basket' end end
6
Merge pull request #125 from iangreenleaf/refactor_trial
4
.rb
rb
mit
splitrb/split
10072301
<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('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('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 '<ul>\n\t<li class="item1"></li>\n\t<!-- /.item1 -->\n\t<li class="item2"></li>\n\t<!-- /.item2 -->\n</ul>'); }); it('reverse attributes merge', () => { equal(expand('a.test'), '<a href="" class="test"></a>'); equal(expand('a.test', { options: { 'output.reverseAttributes': true } }), '<a class="test" href=""></a>'); }); // it.only('debug', () => { // equal(expand('link:css'), '<link rel="stylesheet" href="style.css">'); // }); 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>'); }); it('override attributes', () => { const config = { syntax: 'jsx' }; equal(expand('.bar', config), '<div className="bar"></div>'); 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> Properly merge attribute declarations <DFF> @@ -17,6 +17,29 @@ describe('Expand Abbreviation', () => { }), '<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>'); + + // 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('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 '); @@ -59,11 +82,6 @@ describe('Expand Abbreviation', () => { '<ul>\n\t<li class="item1"></li>\n\t<!-- /.item1 -->\n\t<li class="item2"></li>\n\t<!-- /.item2 -->\n</ul>'); }); - it('reverse attributes merge', () => { - equal(expand('a.test'), '<a href="" class="test"></a>'); - equal(expand('a.test', { options: { 'output.reverseAttributes': true } }), '<a class="test" href=""></a>'); - }); - // it.only('debug', () => { // equal(expand('link:css'), '<link rel="stylesheet" href="style.css">'); // });
23
Properly merge attribute declarations
5
.ts
ts
mit
emmetio/emmet
10072302
<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('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('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 '<ul>\n\t<li class="item1"></li>\n\t<!-- /.item1 -->\n\t<li class="item2"></li>\n\t<!-- /.item2 -->\n</ul>'); }); it('reverse attributes merge', () => { equal(expand('a.test'), '<a href="" class="test"></a>'); equal(expand('a.test', { options: { 'output.reverseAttributes': true } }), '<a class="test" href=""></a>'); }); // it.only('debug', () => { // equal(expand('link:css'), '<link rel="stylesheet" href="style.css">'); // }); 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>'); }); it('override attributes', () => { const config = { syntax: 'jsx' }; equal(expand('.bar', config), '<div className="bar"></div>'); 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> Properly merge attribute declarations <DFF> @@ -17,6 +17,29 @@ describe('Expand Abbreviation', () => { }), '<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>'); + + // 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('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 '); @@ -59,11 +82,6 @@ describe('Expand Abbreviation', () => { '<ul>\n\t<li class="item1"></li>\n\t<!-- /.item1 -->\n\t<li class="item2"></li>\n\t<!-- /.item2 -->\n</ul>'); }); - it('reverse attributes merge', () => { - equal(expand('a.test'), '<a href="" class="test"></a>'); - equal(expand('a.test', { options: { 'output.reverseAttributes': true } }), '<a class="test" href=""></a>'); - }); - // it.only('debug', () => { // equal(expand('link:css'), '<link rel="stylesheet" href="style.css">'); // });
23
Properly merge attribute declarations
5
.ts
ts
mit
emmetio/emmet
10072303
<NME> layout.erb <BEF> <!DOCTYPE html> <html> <head> <meta content='text/html; charset=utf-8' http-equiv='Content-Type'> <link href="<%= url 'reset.css' %>" media="screen" rel="stylesheet" type="text/css"> <link href="<%= url 'style.css' %>" media="screen" rel="stylesheet" type="text/css"> <script type="text/javascript" src='<%= url 'dashboard.js' %>'></script> <script type="text/javascript" src='<%= url 'jquery-1.11.1.min.js' %>'></script> <script type="text/javascript" src='<%= url 'dashboard-filtering.js' %>'></script> <title>Split</title> <body> <div class="header"> <h1>Split Dashboard</h1> </div> <div id="main"> <div id="main"> <%= yield %> </div> <div id="footer"> <p>Powered by <a href="https://github.com/splitrb/split">Split</a> v<%=Split::VERSION %></p> </div> </body> </html> <MSG> Merge pull request #187 from rceee/dashboard-environment Added Rails Environment to Split Admin header <DFF> @@ -11,6 +11,7 @@ <body> <div class="header"> <h1>Split Dashboard</h1> + <p class="environment"><%= Rails.env.titlecase %></p> </div> <div id="main">
1
Merge pull request #187 from rceee/dashboard-environment
0
.erb
erb
mit
splitrb/split
10072304
<NME> layout.erb <BEF> <!DOCTYPE html> <html> <head> <meta content='text/html; charset=utf-8' http-equiv='Content-Type'> <link href="<%= url 'reset.css' %>" media="screen" rel="stylesheet" type="text/css"> <link href="<%= url 'style.css' %>" media="screen" rel="stylesheet" type="text/css"> <script type="text/javascript" src='<%= url 'dashboard.js' %>'></script> <script type="text/javascript" src='<%= url 'jquery-1.11.1.min.js' %>'></script> <script type="text/javascript" src='<%= url 'dashboard-filtering.js' %>'></script> <title>Split</title> <body> <div class="header"> <h1>Split Dashboard</h1> </div> <div id="main"> <div id="main"> <%= yield %> </div> <div id="footer"> <p>Powered by <a href="https://github.com/splitrb/split">Split</a> v<%=Split::VERSION %></p> </div> </body> </html> <MSG> Merge pull request #187 from rceee/dashboard-environment Added Rails Environment to Split Admin header <DFF> @@ -11,6 +11,7 @@ <body> <div class="header"> <h1>Split Dashboard</h1> + <p class="environment"><%= Rails.env.titlecase %></p> </div> <div id="main">
1
Merge pull request #187 from rceee/dashboard-environment
0
.erb
erb
mit
splitrb/split
10072305
<NME> layout.erb <BEF> <!DOCTYPE html> <html> <head> <meta content='text/html; charset=utf-8' http-equiv='Content-Type'> <link href="<%= url 'reset.css' %>" media="screen" rel="stylesheet" type="text/css"> <link href="<%= url 'style.css' %>" media="screen" rel="stylesheet" type="text/css"> <script type="text/javascript" src='<%= url 'dashboard.js' %>'></script> <script type="text/javascript" src='<%= url 'jquery-1.11.1.min.js' %>'></script> <script type="text/javascript" src='<%= url 'dashboard-filtering.js' %>'></script> <title>Split</title> <body> <div class="header"> <h1>Split Dashboard</h1> </div> <div id="main"> <div id="main"> <%= yield %> </div> <div id="footer"> <p>Powered by <a href="https://github.com/splitrb/split">Split</a> v<%=Split::VERSION %></p> </div> </body> </html> <MSG> Merge pull request #187 from rceee/dashboard-environment Added Rails Environment to Split Admin header <DFF> @@ -11,6 +11,7 @@ <body> <div class="header"> <h1>Split Dashboard</h1> + <p class="environment"><%= Rails.env.titlecase %></p> </div> <div id="main">
1
Merge pull request #187 from rceee/dashboard-environment
0
.erb
erb
mit
splitrb/split
10072306
<NME> format.ts <BEF> import { equal } from 'assert'; import html from '../src/markup/format/html'; import haml from '../src/markup/format/haml'; import pug from '../src/markup/format/pug'; import slim from '../src/markup/format/slim'; import parse from '../src/markup'; import createConfig, { Options } from '../src/config'; describe('Format', () => { const defaultConfig = createConfig(); const field = createConfig({ options: { 'output.field': (index, placeholder) => placeholder ? `\${${index}:${placeholder}}` : `\${${index}}` } }); function createProfile(options: Partial<Options>) { const config = createConfig({ options }); return config; } describe('HTML', () => { const format = (abbr: string, config = defaultConfig) => html(parse(abbr, config), config); it('basic', () => { equal(format('div>p'), '<div>\n\t<p></p>\n</div>'); equal(format('div>p*3'), '<div>\n\t<p></p>\n\t<p></p>\n\t<p></p>\n</div>'); equal(format('div#a>p.b*2>span'), '<div id="a">\n\t<p class="b"><span></span></p>\n\t<p class="b"><span></span></p>\n</div>'); equal(format('div>div>div'), '<div>\n\t<div>\n\t\t<div></div>\n\t</div>\n</div>'); equal(format('table>tr*2>td{item}*2'), '<table>\n\t<tr>\n\t\t<td>item</td>\n\t\t<td>item</td>\n\t</tr>\n\t<tr>\n\t\t<td>item</td>\n\t\t<td>item</td>\n\t</tr>\n</table>'); }); it('inline elements', () => { const profile = createProfile({ 'output.inlineBreak': 3 }); const breakInline = createProfile({ 'output.inlineBreak': 1 }); const keepInline = createProfile({ 'output.inlineBreak': 0 }); const xhtml = createProfile({ 'output.selfClosingStyle': 'xhtml' }); equal(format('div>a>b*3', xhtml), '<div>\n\t<a href="">\n\t\t<b></b>\n\t\t<b></b>\n\t\t<b></b>\n\t</a>\n</div>'); equal(format('p>i', profile), '<p><i></i></p>'); equal(format('p>i*2', profile), '<p><i></i><i></i></p>'); equal(format('p>i*2', breakInline), '<p>\n\t<i></i>\n\t<i></i>\n</p>'); equal(format('p>i*3', profile), '<p>\n\t<i></i>\n\t<i></i>\n\t<i></i>\n</p>'); equal(format('p>i*3', keepInline), '<p><i></i><i></i><i></i></p>'); equal(format('i*2', profile), '<i></i><i></i>'); equal(format('i*3', profile), '<i></i>\n<i></i>\n<i></i>'); equal(format('i{a}+i{b}', profile), '<i>a</i><i>b</i>'); equal(format('img[src]/+p', xhtml), '<img src="" alt="" />\n<p></p>'); equal(format('div>img[src]/+p', xhtml), '<div>\n\t<img src="" alt="" />\n\t<p></p>\n</div>'); equal(format('div>p+img[src]/', xhtml), '<div>\n\t<p></p>\n\t<img src="" alt="" />\n</div>'); equal(format('div>p+img[src]/+p', xhtml), '<div>\n\t<p></p>\n\t<img src="" alt="" />\n\t<p></p>\n</div>'); equal(format('div>p+img[src]/*2+p', xhtml), '<div>\n\t<p></p>\n\t<img src="" alt="" /><img src="" alt="" />\n\t<p></p>\n</div>'); equal(format('div>p+img[src]/*3+p', xhtml), '<div>\n\t<p></p>\n\t<img src="" alt="" />\n\t<img src="" alt="" />\n\t<img src="" alt="" />\n\t<p></p>\n</div>'); }); it('generate fields', () => { equal(format('a[href]', field), '<a href="${1}">${2}</a>'); equal(format('a[href]*2', field), '<a href="${1}">${2}</a><a href="${3}">${4}</a>'); equal(format('{${0} ${1:foo} ${2:bar}}*2', field), '${1} ${2:foo} ${3:bar}\n${4} ${5:foo} ${6:bar}'); equal(format('{${0} ${1:foo} ${2:bar}}*2'), ' foo bar\n foo bar'); equal(format('ul>li*2', field), '<ul>\n\t<li>${1}</li>\n\t<li>${2}</li>\n</ul>'); equal(format('div>img[src]/', field), '<div><img src="${1}" alt="${2}"></div>'); }); // it.only('debug', () => { // equal(format('div>{foo}+{bar}+p'), '<div>\n\tfoobar\n\t<p></p>\n</div>'); // }); it('mixed content', () => { equal(format('div{foo}'), '<div>foo</div>'); equal(format('div>{foo}'), '<div>foo</div>'); equal(format('div>{foo}+{bar}'), '<div>\n\tfoo\n\tbar\n</div>'); equal(format('div>{foo}+{bar}+p'), '<div>\n\tfoo\n\tbar\n\t<p></p>\n</div>'); equal(format('div>{foo}+{bar}+p+{foo}+{bar}+p'), '<div>\n\tfoo\n\tbar\n\t<p></p>\n\tfoo\n\tbar\n\t<p></p>\n</div>'); equal(format('div>{foo}+p+{bar}'), '<div>\n\tfoo\n\t<p></p>\n\tbar\n</div>'); equal(format('div>{foo}>p'), '<div>\n\tfoo\n\t<p></p>\n</div>'); equal(format('div>{<!-- ${0} -->}'), '<div><!-- --></div>'); equal(format('div>{<!-- ${0} -->}+p'), '<div>\n\t<!-- -->\n\t<p></p>\n</div>'); equal(format('div>p+{<!-- ${0} -->}'), '<div>\n\t<p></p>\n\t<!-- -->\n</div>'); equal(format('div>{<!-- ${0} -->}>p'), '<div>\n\t<!-- <p></p> -->\n</div>'); equal(format('div>{<!-- ${0} -->}*2>p'), '<div>\n\t<!-- <p></p> -->\n\t<!-- <p></p> -->\n</div>'); equal(format('div>{<!-- ${0} -->}>p*2'), '<div>\n\t<!-- \n\t<p></p>\n\t<p></p>\n\t-->\n</div>'); equal(format('div>{<!-- ${0} -->}*2>p*2'), '<div>\n\t<!-- \n\t<p></p>\n\t<p></p>\n\t-->\n\t<!-- \n\t<p></p>\n\t<p></p>\n\t-->\n</div>'); equal(format('div>{<!-- ${0} -->}', field), '<div><!-- ${1} --></div>'); equal(format('div>{<!-- ${0} -->}>b', field), '<div>\n\t<!-- <b>${1}</b> -->\n</div>'); }); }); }); '<!DOCTYPE html>\n<html>\n<head>\n\t<meta charset="UTF-8">\n\t<title>${2:Document}</title>\n</head>\n<body>\n\t${3}\n</body>\n</html>'); }); it('comment', () => { const opt = createConfig({ options: { 'comment.enabled': true } }); equal(format('ul>li.item', opt), '<ul>\n\t<li class="item"></li>\n\t<!-- /.item -->\n</ul>'); equal(format('div>ul>li.item#foo', opt), '<div>\n\t<ul>\n\t\t<li class="item" id="foo"></li>\n\t\t<!-- /#foo.item -->\n\t</ul>\n</div>'); opt.options['comment.after'] = ' { [%ID] }'; equal(format('div>ul>li.item#foo', opt), '<div>\n\t<ul>\n\t\t<li class="item" id="foo"></li> { %foo }\n\t</ul>\n</div>'); }); }); describe('HAML', () => { const format = (abbr: string, config = defaultConfig) => haml(parse(abbr, config), config); it('basic', () => { equal(format('div#header>ul.nav>li[title=test].nav-item*2'), '#header\n\t%ul.nav\n\t\t%li.nav-item(title="test") \n\t\t%li.nav-item(title="test") '); // https://github.com/emmetio/emmet/issues/446 equal(format('li>a'), '%li\n\t%a(href="") '); equal(format('div#foo[data-n1=v1 title=test data-n2=v2].bar'), '#foo.bar(data-n1="v1" title="test" data-n2="v2") '); let profile = createProfile({ 'output.compactBoolean': true }); equal(format('input[disabled. foo title=test]/', profile), '%input(type="text" disabled foo="" title="test")/'); profile = createProfile({ 'output.compactBoolean': false }); equal(format('input[disabled. foo title=test]/', profile), '%input(type="text" disabled=true foo="" title="test")/'); }); it('nodes with text', () => { equal(format('{Text 1}'), 'Text 1'); equal(format('span{Text 1}'), '%span Text 1'); equal(format('span{Text 1}>b{Text 2}'), '%span Text 1\n\t%b Text 2'); equal(format('span{Text 1\nText 2}>b{Text 3}'), '%span\n\tText 1 |\n\tText 2 |\n\t%b Text 3'); equal(format('div>span{Text 1\nText 2\nText 123}>b{Text 3}'), '%div\n\t%span\n\t\tText 1 |\n\t\tText 2 |\n\t\tText 123 |\n\t\t%b Text 3'); }); it('generate fields', () => { equal(format('a[href]', field), '%a(href="${1}") ${2}'); equal(format('a[href]*2', field), '%a(href="${1}") ${2}\n%a(href="${3}") ${4}'); equal(format('{${0} ${1:foo} ${2:bar}}*2', field), '${1} ${2:foo} ${3:bar}${4} ${5:foo} ${6:bar}'); equal(format('{${0} ${1:foo} ${2:bar}}*2'), ' foo bar foo bar'); equal(format('ul>li*2', field), '%ul\n\t%li ${1}\n\t%li ${2}'); equal(format('div>img[src]/', field), '%div\n\t%img(src="${1}" alt="${2}")/'); }); }); describe('Pug', () => { const format = (abbr: string, config = defaultConfig) => pug(parse(abbr, config), config); it('basic', () => { equal(format('div#header>ul.nav>li[title=test].nav-item*2'), '#header\n\tul.nav\n\t\tli.nav-item(title="test") \n\t\tli.nav-item(title="test") '); equal(format('div#foo[data-n1=v1 title=test data-n2=v2].bar'), '#foo.bar(data-n1="v1", title="test", data-n2="v2") '); equal(format('input[disabled. foo title=test]'), 'input(type="text", disabled, foo="", title="test")'); // Use closing slash for XML output format equal(format('input[disabled. foo title=test]', createProfile({ 'output.selfClosingStyle': 'xml' })), 'input(type="text", disabled, foo="", title="test")/'); }); it('nodes with text', () => { equal(format('{Text 1}'), 'Text 1'); equal(format('span{Text 1}'), 'span Text 1'); equal(format('span{Text 1}>b{Text 2}'), 'span Text 1\n\tb Text 2'); equal(format('span{Text 1\nText 2}>b{Text 3}'), 'span\n\t| Text 1\n\t| Text 2\n\tb Text 3'); equal(format('div>span{Text 1\nText 2}>b{Text 3}'), 'div\n\tspan\n\t\t| Text 1\n\t\t| Text 2\n\t\tb Text 3'); }); it('generate fields', () => { equal(format('a[href]', field), 'a(href="${1}") ${2}'); equal(format('a[href]*2', field), 'a(href="${1}") ${2}\na(href="${3}") ${4}'); equal(format('{${0} ${1:foo} ${2:bar}}*2', field), '${1} ${2:foo} ${3:bar}${4} ${5:foo} ${6:bar}'); equal(format('{${0} ${1:foo} ${2:bar}}*2'), ' foo bar foo bar'); equal(format('ul>li*2', field), 'ul\n\tli ${1}\n\tli ${2}'); equal(format('div>img[src]/', field), 'div\n\timg(src="${1}", alt="${2}")'); }); }); describe('Slim', () => { const format = (abbr: string, config = defaultConfig) => slim(parse(abbr, config), config); it('basic', () => { equal(format('div#header>ul.nav>li[title=test].nav-item*2'), '#header\n\tul.nav\n\t\tli.nav-item title="test" \n\t\tli.nav-item title="test" '); equal(format('div#foo[data-n1=v1 title=test data-n2=v2].bar'), '#foo.bar data-n1="v1" title="test" data-n2="v2" '); // const profile = createProfile({ inlineBreak: 0 }); // equal(format('ul>li>span{Text}', profile), 'ul\n\tli: span Text'); // equal(format('ul>li>span{Text}'), 'ul\n\tli\n\t\tspan Text'); // equal(format('ul>li>span{Text}*2', profile), 'ul\n\tli\n\t\tspan Text\n\t\tspan Text'); }); // it.skip('attribute wrappers', () => { // equal(format('input[disabled. foo title=test]'), 'input disabled=true foo="" title="test"'); // equal(format('input[disabled. foo title=test]', null, { attributeWrap: 'round' }), // 'input(disabled foo="" title="test")'); // }); it('nodes with text', () => { equal(format('{Text 1}'), 'Text 1'); equal(format('span{Text 1}'), 'span Text 1'); equal(format('span{Text 1}>b{Text 2}'), 'span Text 1\n\tb Text 2'); equal(format('span{Text 1\nText 2}>b{Text 3}'), 'span\n\t| Text 1\n\t| Text 2\n\tb Text 3'); equal(format('div>span{Text 1\nText 2}>b{Text 3}'), 'div\n\tspan\n\t\t| Text 1\n\t\t| Text 2\n\t\tb Text 3'); }); it('generate fields', () => { equal(format('a[href]', field), 'a href="${1}" ${2}'); equal(format('a[href]*2', field), 'a href="${1}" ${2}\na href="${3}" ${4}'); equal(format('{${0} ${1:foo} ${2:bar}}*2', field), '${1} ${2:foo} ${3:bar}${4} ${5:foo} ${6:bar}'); equal(format('{${0} ${1:foo} ${2:bar}}*2'), ' foo bar foo bar'); equal(format('ul>li*2', field), 'ul\n\tli ${1}\n\tli ${2}'); equal(format('div>img[src]/', field), 'div\n\timg src="${1}" alt="${2}"/'); }); }); }); <MSG> Support all HTML unit tests <DFF> @@ -91,5 +91,40 @@ describe('Format', () => { equal(format('div>{<!-- ${0} -->}', field), '<div><!-- ${1} --></div>'); equal(format('div>{<!-- ${0} -->}>b', field), '<div>\n\t<!-- <b>${1}</b> -->\n</div>'); }); + + it('self-closing', () => { + const xmlStyle = createProfile({ selfClosingStyle: 'xml' }); + const htmlStyle = createProfile({ selfClosingStyle: 'html' }); + const xhtmlStyle = createProfile({ selfClosingStyle: 'xhtml' }); + + equal(format('img[src]/', htmlStyle), '<img src="" alt="">'); + equal(format('img[src]/', xhtmlStyle), '<img src="" alt="" />'); + equal(format('img[src]/', xmlStyle), '<img src="" alt=""/>'); + equal(format('div>img[src]/', xhtmlStyle), '<div><img src="" alt="" /></div>'); + }); + + it('boolean attributes', () => { + const compact = createProfile({ compactBoolean: true }); + const noCompact = createProfile({ compactBoolean: false }); + + equal(format('p[b.]', noCompact), '<p b="b"></p>'); + equal(format('p[b.]', compact), '<p b></p>'); + equal(format('p[contenteditable]', compact), '<p contenteditable></p>'); + equal(format('p[contenteditable]', noCompact), '<p contenteditable="contenteditable"></p>'); + equal(format('p[contenteditable=foo]', compact), '<p contenteditable="foo"></p>'); + }); + + it('no formatting', () => { + const profile = createProfile({ format: false }); + equal(format('div>p', profile), '<div><p></p></div>'); + equal(format('div>{foo}+p+{bar}', profile), '<div>foo<p></p>bar</div>'); + equal(format('div>{foo}>p', profile), '<div>foo<p></p></div>'); + equal(format('div>{<!-- ${0} -->}>p', profile), '<div><!-- <p></p> --></div>'); + }); + + it('format specific nodes', () => { + equal(format('{<!DOCTYPE html>}+html>(head>meta[charset=${charset}]/+title{${1:Document}})+body', field), + '<!DOCTYPE html>\n<html>\n<head>\n\t<meta charset="charset">\n\t<title>${2:Document}</title>\n</head>\n<body>\n\t${3}\n</body>\n</html>'); + }); }); });
35
Support all HTML unit tests
0
.ts
ts
mit
emmetio/emmet
10072307
<NME> format.ts <BEF> import { equal } from 'assert'; import html from '../src/markup/format/html'; import haml from '../src/markup/format/haml'; import pug from '../src/markup/format/pug'; import slim from '../src/markup/format/slim'; import parse from '../src/markup'; import createConfig, { Options } from '../src/config'; describe('Format', () => { const defaultConfig = createConfig(); const field = createConfig({ options: { 'output.field': (index, placeholder) => placeholder ? `\${${index}:${placeholder}}` : `\${${index}}` } }); function createProfile(options: Partial<Options>) { const config = createConfig({ options }); return config; } describe('HTML', () => { const format = (abbr: string, config = defaultConfig) => html(parse(abbr, config), config); it('basic', () => { equal(format('div>p'), '<div>\n\t<p></p>\n</div>'); equal(format('div>p*3'), '<div>\n\t<p></p>\n\t<p></p>\n\t<p></p>\n</div>'); equal(format('div#a>p.b*2>span'), '<div id="a">\n\t<p class="b"><span></span></p>\n\t<p class="b"><span></span></p>\n</div>'); equal(format('div>div>div'), '<div>\n\t<div>\n\t\t<div></div>\n\t</div>\n</div>'); equal(format('table>tr*2>td{item}*2'), '<table>\n\t<tr>\n\t\t<td>item</td>\n\t\t<td>item</td>\n\t</tr>\n\t<tr>\n\t\t<td>item</td>\n\t\t<td>item</td>\n\t</tr>\n</table>'); }); it('inline elements', () => { const profile = createProfile({ 'output.inlineBreak': 3 }); const breakInline = createProfile({ 'output.inlineBreak': 1 }); const keepInline = createProfile({ 'output.inlineBreak': 0 }); const xhtml = createProfile({ 'output.selfClosingStyle': 'xhtml' }); equal(format('div>a>b*3', xhtml), '<div>\n\t<a href="">\n\t\t<b></b>\n\t\t<b></b>\n\t\t<b></b>\n\t</a>\n</div>'); equal(format('p>i', profile), '<p><i></i></p>'); equal(format('p>i*2', profile), '<p><i></i><i></i></p>'); equal(format('p>i*2', breakInline), '<p>\n\t<i></i>\n\t<i></i>\n</p>'); equal(format('p>i*3', profile), '<p>\n\t<i></i>\n\t<i></i>\n\t<i></i>\n</p>'); equal(format('p>i*3', keepInline), '<p><i></i><i></i><i></i></p>'); equal(format('i*2', profile), '<i></i><i></i>'); equal(format('i*3', profile), '<i></i>\n<i></i>\n<i></i>'); equal(format('i{a}+i{b}', profile), '<i>a</i><i>b</i>'); equal(format('img[src]/+p', xhtml), '<img src="" alt="" />\n<p></p>'); equal(format('div>img[src]/+p', xhtml), '<div>\n\t<img src="" alt="" />\n\t<p></p>\n</div>'); equal(format('div>p+img[src]/', xhtml), '<div>\n\t<p></p>\n\t<img src="" alt="" />\n</div>'); equal(format('div>p+img[src]/+p', xhtml), '<div>\n\t<p></p>\n\t<img src="" alt="" />\n\t<p></p>\n</div>'); equal(format('div>p+img[src]/*2+p', xhtml), '<div>\n\t<p></p>\n\t<img src="" alt="" /><img src="" alt="" />\n\t<p></p>\n</div>'); equal(format('div>p+img[src]/*3+p', xhtml), '<div>\n\t<p></p>\n\t<img src="" alt="" />\n\t<img src="" alt="" />\n\t<img src="" alt="" />\n\t<p></p>\n</div>'); }); it('generate fields', () => { equal(format('a[href]', field), '<a href="${1}">${2}</a>'); equal(format('a[href]*2', field), '<a href="${1}">${2}</a><a href="${3}">${4}</a>'); equal(format('{${0} ${1:foo} ${2:bar}}*2', field), '${1} ${2:foo} ${3:bar}\n${4} ${5:foo} ${6:bar}'); equal(format('{${0} ${1:foo} ${2:bar}}*2'), ' foo bar\n foo bar'); equal(format('ul>li*2', field), '<ul>\n\t<li>${1}</li>\n\t<li>${2}</li>\n</ul>'); equal(format('div>img[src]/', field), '<div><img src="${1}" alt="${2}"></div>'); }); // it.only('debug', () => { // equal(format('div>{foo}+{bar}+p'), '<div>\n\tfoobar\n\t<p></p>\n</div>'); // }); it('mixed content', () => { equal(format('div{foo}'), '<div>foo</div>'); equal(format('div>{foo}'), '<div>foo</div>'); equal(format('div>{foo}+{bar}'), '<div>\n\tfoo\n\tbar\n</div>'); equal(format('div>{foo}+{bar}+p'), '<div>\n\tfoo\n\tbar\n\t<p></p>\n</div>'); equal(format('div>{foo}+{bar}+p+{foo}+{bar}+p'), '<div>\n\tfoo\n\tbar\n\t<p></p>\n\tfoo\n\tbar\n\t<p></p>\n</div>'); equal(format('div>{foo}+p+{bar}'), '<div>\n\tfoo\n\t<p></p>\n\tbar\n</div>'); equal(format('div>{foo}>p'), '<div>\n\tfoo\n\t<p></p>\n</div>'); equal(format('div>{<!-- ${0} -->}'), '<div><!-- --></div>'); equal(format('div>{<!-- ${0} -->}+p'), '<div>\n\t<!-- -->\n\t<p></p>\n</div>'); equal(format('div>p+{<!-- ${0} -->}'), '<div>\n\t<p></p>\n\t<!-- -->\n</div>'); equal(format('div>{<!-- ${0} -->}>p'), '<div>\n\t<!-- <p></p> -->\n</div>'); equal(format('div>{<!-- ${0} -->}*2>p'), '<div>\n\t<!-- <p></p> -->\n\t<!-- <p></p> -->\n</div>'); equal(format('div>{<!-- ${0} -->}>p*2'), '<div>\n\t<!-- \n\t<p></p>\n\t<p></p>\n\t-->\n</div>'); equal(format('div>{<!-- ${0} -->}*2>p*2'), '<div>\n\t<!-- \n\t<p></p>\n\t<p></p>\n\t-->\n\t<!-- \n\t<p></p>\n\t<p></p>\n\t-->\n</div>'); equal(format('div>{<!-- ${0} -->}', field), '<div><!-- ${1} --></div>'); equal(format('div>{<!-- ${0} -->}>b', field), '<div>\n\t<!-- <b>${1}</b> -->\n</div>'); }); }); }); '<!DOCTYPE html>\n<html>\n<head>\n\t<meta charset="UTF-8">\n\t<title>${2:Document}</title>\n</head>\n<body>\n\t${3}\n</body>\n</html>'); }); it('comment', () => { const opt = createConfig({ options: { 'comment.enabled': true } }); equal(format('ul>li.item', opt), '<ul>\n\t<li class="item"></li>\n\t<!-- /.item -->\n</ul>'); equal(format('div>ul>li.item#foo', opt), '<div>\n\t<ul>\n\t\t<li class="item" id="foo"></li>\n\t\t<!-- /#foo.item -->\n\t</ul>\n</div>'); opt.options['comment.after'] = ' { [%ID] }'; equal(format('div>ul>li.item#foo', opt), '<div>\n\t<ul>\n\t\t<li class="item" id="foo"></li> { %foo }\n\t</ul>\n</div>'); }); }); describe('HAML', () => { const format = (abbr: string, config = defaultConfig) => haml(parse(abbr, config), config); it('basic', () => { equal(format('div#header>ul.nav>li[title=test].nav-item*2'), '#header\n\t%ul.nav\n\t\t%li.nav-item(title="test") \n\t\t%li.nav-item(title="test") '); // https://github.com/emmetio/emmet/issues/446 equal(format('li>a'), '%li\n\t%a(href="") '); equal(format('div#foo[data-n1=v1 title=test data-n2=v2].bar'), '#foo.bar(data-n1="v1" title="test" data-n2="v2") '); let profile = createProfile({ 'output.compactBoolean': true }); equal(format('input[disabled. foo title=test]/', profile), '%input(type="text" disabled foo="" title="test")/'); profile = createProfile({ 'output.compactBoolean': false }); equal(format('input[disabled. foo title=test]/', profile), '%input(type="text" disabled=true foo="" title="test")/'); }); it('nodes with text', () => { equal(format('{Text 1}'), 'Text 1'); equal(format('span{Text 1}'), '%span Text 1'); equal(format('span{Text 1}>b{Text 2}'), '%span Text 1\n\t%b Text 2'); equal(format('span{Text 1\nText 2}>b{Text 3}'), '%span\n\tText 1 |\n\tText 2 |\n\t%b Text 3'); equal(format('div>span{Text 1\nText 2\nText 123}>b{Text 3}'), '%div\n\t%span\n\t\tText 1 |\n\t\tText 2 |\n\t\tText 123 |\n\t\t%b Text 3'); }); it('generate fields', () => { equal(format('a[href]', field), '%a(href="${1}") ${2}'); equal(format('a[href]*2', field), '%a(href="${1}") ${2}\n%a(href="${3}") ${4}'); equal(format('{${0} ${1:foo} ${2:bar}}*2', field), '${1} ${2:foo} ${3:bar}${4} ${5:foo} ${6:bar}'); equal(format('{${0} ${1:foo} ${2:bar}}*2'), ' foo bar foo bar'); equal(format('ul>li*2', field), '%ul\n\t%li ${1}\n\t%li ${2}'); equal(format('div>img[src]/', field), '%div\n\t%img(src="${1}" alt="${2}")/'); }); }); describe('Pug', () => { const format = (abbr: string, config = defaultConfig) => pug(parse(abbr, config), config); it('basic', () => { equal(format('div#header>ul.nav>li[title=test].nav-item*2'), '#header\n\tul.nav\n\t\tli.nav-item(title="test") \n\t\tli.nav-item(title="test") '); equal(format('div#foo[data-n1=v1 title=test data-n2=v2].bar'), '#foo.bar(data-n1="v1", title="test", data-n2="v2") '); equal(format('input[disabled. foo title=test]'), 'input(type="text", disabled, foo="", title="test")'); // Use closing slash for XML output format equal(format('input[disabled. foo title=test]', createProfile({ 'output.selfClosingStyle': 'xml' })), 'input(type="text", disabled, foo="", title="test")/'); }); it('nodes with text', () => { equal(format('{Text 1}'), 'Text 1'); equal(format('span{Text 1}'), 'span Text 1'); equal(format('span{Text 1}>b{Text 2}'), 'span Text 1\n\tb Text 2'); equal(format('span{Text 1\nText 2}>b{Text 3}'), 'span\n\t| Text 1\n\t| Text 2\n\tb Text 3'); equal(format('div>span{Text 1\nText 2}>b{Text 3}'), 'div\n\tspan\n\t\t| Text 1\n\t\t| Text 2\n\t\tb Text 3'); }); it('generate fields', () => { equal(format('a[href]', field), 'a(href="${1}") ${2}'); equal(format('a[href]*2', field), 'a(href="${1}") ${2}\na(href="${3}") ${4}'); equal(format('{${0} ${1:foo} ${2:bar}}*2', field), '${1} ${2:foo} ${3:bar}${4} ${5:foo} ${6:bar}'); equal(format('{${0} ${1:foo} ${2:bar}}*2'), ' foo bar foo bar'); equal(format('ul>li*2', field), 'ul\n\tli ${1}\n\tli ${2}'); equal(format('div>img[src]/', field), 'div\n\timg(src="${1}", alt="${2}")'); }); }); describe('Slim', () => { const format = (abbr: string, config = defaultConfig) => slim(parse(abbr, config), config); it('basic', () => { equal(format('div#header>ul.nav>li[title=test].nav-item*2'), '#header\n\tul.nav\n\t\tli.nav-item title="test" \n\t\tli.nav-item title="test" '); equal(format('div#foo[data-n1=v1 title=test data-n2=v2].bar'), '#foo.bar data-n1="v1" title="test" data-n2="v2" '); // const profile = createProfile({ inlineBreak: 0 }); // equal(format('ul>li>span{Text}', profile), 'ul\n\tli: span Text'); // equal(format('ul>li>span{Text}'), 'ul\n\tli\n\t\tspan Text'); // equal(format('ul>li>span{Text}*2', profile), 'ul\n\tli\n\t\tspan Text\n\t\tspan Text'); }); // it.skip('attribute wrappers', () => { // equal(format('input[disabled. foo title=test]'), 'input disabled=true foo="" title="test"'); // equal(format('input[disabled. foo title=test]', null, { attributeWrap: 'round' }), // 'input(disabled foo="" title="test")'); // }); it('nodes with text', () => { equal(format('{Text 1}'), 'Text 1'); equal(format('span{Text 1}'), 'span Text 1'); equal(format('span{Text 1}>b{Text 2}'), 'span Text 1\n\tb Text 2'); equal(format('span{Text 1\nText 2}>b{Text 3}'), 'span\n\t| Text 1\n\t| Text 2\n\tb Text 3'); equal(format('div>span{Text 1\nText 2}>b{Text 3}'), 'div\n\tspan\n\t\t| Text 1\n\t\t| Text 2\n\t\tb Text 3'); }); it('generate fields', () => { equal(format('a[href]', field), 'a href="${1}" ${2}'); equal(format('a[href]*2', field), 'a href="${1}" ${2}\na href="${3}" ${4}'); equal(format('{${0} ${1:foo} ${2:bar}}*2', field), '${1} ${2:foo} ${3:bar}${4} ${5:foo} ${6:bar}'); equal(format('{${0} ${1:foo} ${2:bar}}*2'), ' foo bar foo bar'); equal(format('ul>li*2', field), 'ul\n\tli ${1}\n\tli ${2}'); equal(format('div>img[src]/', field), 'div\n\timg src="${1}" alt="${2}"/'); }); }); }); <MSG> Support all HTML unit tests <DFF> @@ -91,5 +91,40 @@ describe('Format', () => { equal(format('div>{<!-- ${0} -->}', field), '<div><!-- ${1} --></div>'); equal(format('div>{<!-- ${0} -->}>b', field), '<div>\n\t<!-- <b>${1}</b> -->\n</div>'); }); + + it('self-closing', () => { + const xmlStyle = createProfile({ selfClosingStyle: 'xml' }); + const htmlStyle = createProfile({ selfClosingStyle: 'html' }); + const xhtmlStyle = createProfile({ selfClosingStyle: 'xhtml' }); + + equal(format('img[src]/', htmlStyle), '<img src="" alt="">'); + equal(format('img[src]/', xhtmlStyle), '<img src="" alt="" />'); + equal(format('img[src]/', xmlStyle), '<img src="" alt=""/>'); + equal(format('div>img[src]/', xhtmlStyle), '<div><img src="" alt="" /></div>'); + }); + + it('boolean attributes', () => { + const compact = createProfile({ compactBoolean: true }); + const noCompact = createProfile({ compactBoolean: false }); + + equal(format('p[b.]', noCompact), '<p b="b"></p>'); + equal(format('p[b.]', compact), '<p b></p>'); + equal(format('p[contenteditable]', compact), '<p contenteditable></p>'); + equal(format('p[contenteditable]', noCompact), '<p contenteditable="contenteditable"></p>'); + equal(format('p[contenteditable=foo]', compact), '<p contenteditable="foo"></p>'); + }); + + it('no formatting', () => { + const profile = createProfile({ format: false }); + equal(format('div>p', profile), '<div><p></p></div>'); + equal(format('div>{foo}+p+{bar}', profile), '<div>foo<p></p>bar</div>'); + equal(format('div>{foo}>p', profile), '<div>foo<p></p></div>'); + equal(format('div>{<!-- ${0} -->}>p', profile), '<div><!-- <p></p> --></div>'); + }); + + it('format specific nodes', () => { + equal(format('{<!DOCTYPE html>}+html>(head>meta[charset=${charset}]/+title{${1:Document}})+body', field), + '<!DOCTYPE html>\n<html>\n<head>\n\t<meta charset="charset">\n\t<title>${2:Document}</title>\n</head>\n<body>\n\t${3}\n</body>\n</html>'); + }); }); });
35
Support all HTML unit tests
0
.ts
ts
mit
emmetio/emmet
10072308
<NME> .gitignore <BEF> .idea *.html.js .DS_Store .grunt /node_modules /dist *-SNAPSHOT* typings npm-debug.log .vscode <MSG> chore(project): ignore js and map files in src <DFF> @@ -7,4 +7,6 @@ *-SNAPSHOT* typings npm-debug.log -.vscode \ No newline at end of file +.vscode +src/**/*.js +src/**/*.map
3
chore(project): ignore js and map files in src
1
gitignore
mit
Semantic-Org/Semantic-UI-Angular
10072309
<NME> .gitignore <BEF> .idea *.html.js .DS_Store .grunt /node_modules /dist *-SNAPSHOT* typings npm-debug.log .vscode <MSG> chore(project): ignore js and map files in src <DFF> @@ -7,4 +7,6 @@ *-SNAPSHOT* typings npm-debug.log -.vscode \ No newline at end of file +.vscode +src/**/*.js +src/**/*.map
3
chore(project): ignore js and map files in src
1
gitignore
mit
Semantic-Org/Semantic-UI-Angular
10072310
<NME> .gitignore <BEF> .idea *.html.js .DS_Store .grunt /node_modules /dist *-SNAPSHOT* typings npm-debug.log .vscode <MSG> chore(project): ignore js and map files in src <DFF> @@ -7,4 +7,6 @@ *-SNAPSHOT* typings npm-debug.log -.vscode \ No newline at end of file +.vscode +src/**/*.js +src/**/*.map
3
chore(project): ignore js and map files in src
1
gitignore
mit
Semantic-Org/Semantic-UI-Angular
10072311
<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 'Slurp' => 'Yahoo spider', 'WordPress' => 'WordPress spider', 'ZIBB' => 'ZIBB spider', 'Zyborg' => 'Zyborg? Hmmm....' } attr_accessor :robot_regex attr_accessor :ignore_ip_addresses 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 attr_accessor :on_before_experiment_delete attr_accessor :include_rails_helper attr_accessor :beta_probability_simulations attr_accessor :winning_alternative_recalculation_interval attr_accessor :redis attr_accessor :dashboard_pagination_default_per_page attr_accessor :cache attr_reader :experiments attr_writer :bots attr_writer :robot_regex 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", "bot@linkfluence.net" => "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> corrected final typo in robots hash <DFF> @@ -11,7 +11,7 @@ module Split 'Slurp' => 'Yahoo spider', 'WordPress' => 'WordPress spider', 'ZIBB' => 'ZIBB spider', - 'Zyborg' => 'Zyborg? Hmmm....' + 'ZyBorg' => 'Zyborg? Hmmm....' } attr_accessor :robot_regex attr_accessor :ignore_ip_addresses
1
corrected final typo in robots hash
1
.rb
rb
mit
splitrb/split
10072312
<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 'Slurp' => 'Yahoo spider', 'WordPress' => 'WordPress spider', 'ZIBB' => 'ZIBB spider', 'Zyborg' => 'Zyborg? Hmmm....' } attr_accessor :robot_regex attr_accessor :ignore_ip_addresses 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 attr_accessor :on_before_experiment_delete attr_accessor :include_rails_helper attr_accessor :beta_probability_simulations attr_accessor :winning_alternative_recalculation_interval attr_accessor :redis attr_accessor :dashboard_pagination_default_per_page attr_accessor :cache attr_reader :experiments attr_writer :bots attr_writer :robot_regex 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", "bot@linkfluence.net" => "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> corrected final typo in robots hash <DFF> @@ -11,7 +11,7 @@ module Split 'Slurp' => 'Yahoo spider', 'WordPress' => 'WordPress spider', 'ZIBB' => 'ZIBB spider', - 'Zyborg' => 'Zyborg? Hmmm....' + 'ZyBorg' => 'Zyborg? Hmmm....' } attr_accessor :robot_regex attr_accessor :ignore_ip_addresses
1
corrected final typo in robots hash
1
.rb
rb
mit
splitrb/split
10072313
<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 'Slurp' => 'Yahoo spider', 'WordPress' => 'WordPress spider', 'ZIBB' => 'ZIBB spider', 'Zyborg' => 'Zyborg? Hmmm....' } attr_accessor :robot_regex attr_accessor :ignore_ip_addresses 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 attr_accessor :on_before_experiment_delete attr_accessor :include_rails_helper attr_accessor :beta_probability_simulations attr_accessor :winning_alternative_recalculation_interval attr_accessor :redis attr_accessor :dashboard_pagination_default_per_page attr_accessor :cache attr_reader :experiments attr_writer :bots attr_writer :robot_regex 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", "bot@linkfluence.net" => "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> corrected final typo in robots hash <DFF> @@ -11,7 +11,7 @@ module Split 'Slurp' => 'Yahoo spider', 'WordPress' => 'WordPress spider', 'ZIBB' => 'ZIBB spider', - 'Zyborg' => 'Zyborg? Hmmm....' + 'ZyBorg' => 'Zyborg? Hmmm....' } attr_accessor :robot_regex attr_accessor :ignore_ip_addresses
1
corrected final typo in robots hash
1
.rb
rb
mit
splitrb/split
10072314
<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> Cleanup old experiments only once during the lifetime of a User instance <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
Cleanup old experiments only once during the lifetime of a User instance
0
.rb
rb
mit
splitrb/split
10072315
<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> Cleanup old experiments only once during the lifetime of a User instance <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
Cleanup old experiments only once during the lifetime of a User instance
0
.rb
rb
mit
splitrb/split
10072316
<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> Cleanup old experiments only once during the lifetime of a User instance <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
Cleanup old experiments only once during the lifetime of a User instance
0
.rb
rb
mit
splitrb/split
10072317
<NME> button.js <BEF> ///<reference path="../../../typings/angularjs/angular.d.ts"/> ///<reference path="../../../typings/angularjs/angular-animate.d.ts"/> 'use strict'; var SmButtonController = (function () { function SmButtonController($animate) { .directive('smButton', smButton); function smButton() { return { restrict:'E', replace: true, this.replace = true; this.transclude = true; link: function(scope, element, attrs, ctrl, transclude) { var node = element[0]; transclude(function(nodes) { element.append(nodes); }); if (_this.isAnchorBtn(attrs)) { scope.$watch(attrs.ngDisabled, function(isDisabled) { element.attr('tabindex', isDisabled ? -1 : 0); if (isDisabled) { element.addClass('disabled'); } }); } if (attrs.ariaLabel === void 0) { element.attr('aria-label', node.textContent.trim()); } scope.$watch(attrs.ngDisabled, function (isDisabled) { scope.$watch(attrs.ngDisabled, function(isDisabled) { if (isDisabled) { element.addClass('disabled'); } }); } }; } SmButtonDirective.instance = function () { return new SmButtonDirective; }; SmButtonDirective.prototype.isAnchorBtn = function (attrs) { return attrs.href !== void 0 || attrs.ngHref !== void 0 || attrs.xlinkHref !== void 0; }; SmButtonDirective.prototype.setTemplate = function (element, attrs) { if (this.isAnchorBtn(attrs)) { return '<a class="ui button"></a>'; } else { return '<button class="ui button"></button>'; } }; return SmButtonDirective; })(); exports.smButtonModule = angular .module('semantic.ui.elements.button', []) .directive('smButton', SmButtonDirective.instance); <MSG> refactor(smButton): Use to manage css classes <DFF> @@ -6,7 +6,9 @@ angular .directive('smButton', smButton); - function smButton() { + smButton['$inject'] = ['$animate']; + + function smButton($animate) { return { restrict:'E', replace: true, @@ -15,7 +17,7 @@ angular link: function(scope, element, attrs, ctrl, transclude) { var node = element[0]; - transclude(function(nodes) { + transclude(scope, function(nodes) { element.append(nodes); }); @@ -23,7 +25,7 @@ angular scope.$watch(attrs.ngDisabled, function(isDisabled) { element.attr('tabindex', isDisabled ? -1 : 0); if (isDisabled) { - element.addClass('disabled'); + $animate.addClass(element, 'disabled'); } }); } @@ -34,7 +36,7 @@ angular scope.$watch(attrs.ngDisabled, function(isDisabled) { if (isDisabled) { - element.addClass('disabled'); + $animate.addClass(element, 'disabled'); } }); }
6
refactor(smButton): Use to manage css classes
4
.js
js
mit
Semantic-Org/Semantic-UI-Angular
10072318
<NME> button.js <BEF> ///<reference path="../../../typings/angularjs/angular.d.ts"/> ///<reference path="../../../typings/angularjs/angular-animate.d.ts"/> 'use strict'; var SmButtonController = (function () { function SmButtonController($animate) { .directive('smButton', smButton); function smButton() { return { restrict:'E', replace: true, this.replace = true; this.transclude = true; link: function(scope, element, attrs, ctrl, transclude) { var node = element[0]; transclude(function(nodes) { element.append(nodes); }); if (_this.isAnchorBtn(attrs)) { scope.$watch(attrs.ngDisabled, function(isDisabled) { element.attr('tabindex', isDisabled ? -1 : 0); if (isDisabled) { element.addClass('disabled'); } }); } if (attrs.ariaLabel === void 0) { element.attr('aria-label', node.textContent.trim()); } scope.$watch(attrs.ngDisabled, function (isDisabled) { scope.$watch(attrs.ngDisabled, function(isDisabled) { if (isDisabled) { element.addClass('disabled'); } }); } }; } SmButtonDirective.instance = function () { return new SmButtonDirective; }; SmButtonDirective.prototype.isAnchorBtn = function (attrs) { return attrs.href !== void 0 || attrs.ngHref !== void 0 || attrs.xlinkHref !== void 0; }; SmButtonDirective.prototype.setTemplate = function (element, attrs) { if (this.isAnchorBtn(attrs)) { return '<a class="ui button"></a>'; } else { return '<button class="ui button"></button>'; } }; return SmButtonDirective; })(); exports.smButtonModule = angular .module('semantic.ui.elements.button', []) .directive('smButton', SmButtonDirective.instance); <MSG> refactor(smButton): Use to manage css classes <DFF> @@ -6,7 +6,9 @@ angular .directive('smButton', smButton); - function smButton() { + smButton['$inject'] = ['$animate']; + + function smButton($animate) { return { restrict:'E', replace: true, @@ -15,7 +17,7 @@ angular link: function(scope, element, attrs, ctrl, transclude) { var node = element[0]; - transclude(function(nodes) { + transclude(scope, function(nodes) { element.append(nodes); }); @@ -23,7 +25,7 @@ angular scope.$watch(attrs.ngDisabled, function(isDisabled) { element.attr('tabindex', isDisabled ? -1 : 0); if (isDisabled) { - element.addClass('disabled'); + $animate.addClass(element, 'disabled'); } }); } @@ -34,7 +36,7 @@ angular scope.$watch(attrs.ngDisabled, function(isDisabled) { if (isDisabled) { - element.addClass('disabled'); + $animate.addClass(element, 'disabled'); } }); }
6
refactor(smButton): Use to manage css classes
4
.js
js
mit
Semantic-Org/Semantic-UI-Angular
10072319
<NME> button.js <BEF> ///<reference path="../../../typings/angularjs/angular.d.ts"/> ///<reference path="../../../typings/angularjs/angular-animate.d.ts"/> 'use strict'; var SmButtonController = (function () { function SmButtonController($animate) { .directive('smButton', smButton); function smButton() { return { restrict:'E', replace: true, this.replace = true; this.transclude = true; link: function(scope, element, attrs, ctrl, transclude) { var node = element[0]; transclude(function(nodes) { element.append(nodes); }); if (_this.isAnchorBtn(attrs)) { scope.$watch(attrs.ngDisabled, function(isDisabled) { element.attr('tabindex', isDisabled ? -1 : 0); if (isDisabled) { element.addClass('disabled'); } }); } if (attrs.ariaLabel === void 0) { element.attr('aria-label', node.textContent.trim()); } scope.$watch(attrs.ngDisabled, function (isDisabled) { scope.$watch(attrs.ngDisabled, function(isDisabled) { if (isDisabled) { element.addClass('disabled'); } }); } }; } SmButtonDirective.instance = function () { return new SmButtonDirective; }; SmButtonDirective.prototype.isAnchorBtn = function (attrs) { return attrs.href !== void 0 || attrs.ngHref !== void 0 || attrs.xlinkHref !== void 0; }; SmButtonDirective.prototype.setTemplate = function (element, attrs) { if (this.isAnchorBtn(attrs)) { return '<a class="ui button"></a>'; } else { return '<button class="ui button"></button>'; } }; return SmButtonDirective; })(); exports.smButtonModule = angular .module('semantic.ui.elements.button', []) .directive('smButton', SmButtonDirective.instance); <MSG> refactor(smButton): Use to manage css classes <DFF> @@ -6,7 +6,9 @@ angular .directive('smButton', smButton); - function smButton() { + smButton['$inject'] = ['$animate']; + + function smButton($animate) { return { restrict:'E', replace: true, @@ -15,7 +17,7 @@ angular link: function(scope, element, attrs, ctrl, transclude) { var node = element[0]; - transclude(function(nodes) { + transclude(scope, function(nodes) { element.append(nodes); }); @@ -23,7 +25,7 @@ angular scope.$watch(attrs.ngDisabled, function(isDisabled) { element.attr('tabindex', isDisabled ? -1 : 0); if (isDisabled) { - element.addClass('disabled'); + $animate.addClass(element, 'disabled'); } }); } @@ -34,7 +36,7 @@ angular scope.$watch(attrs.ngDisabled, function(isDisabled) { if (isDisabled) { - element.addClass('disabled'); + $animate.addClass(element, 'disabled'); } }); }
6
refactor(smButton): Use to manage css classes
4
.js
js
mit
Semantic-Org/Semantic-UI-Angular
10072320
<NME> .gitignore <BEF> ADDFILE <MSG> chore(.gitignore): ignore some common files <DFF> @@ -0,0 +1,7 @@ +*.html.js +.DS_Store +.grunt +/node_modules +/dist +*-SNAPSHOT* +
7
chore(.gitignore): ignore some common files
0
gitignore
mit
Semantic-Org/Semantic-UI-Angular
10072321
<NME> .gitignore <BEF> ADDFILE <MSG> chore(.gitignore): ignore some common files <DFF> @@ -0,0 +1,7 @@ +*.html.js +.DS_Store +.grunt +/node_modules +/dist +*-SNAPSHOT* +
7
chore(.gitignore): ignore some common files
0
gitignore
mit
Semantic-Org/Semantic-UI-Angular
10072322
<NME> .gitignore <BEF> ADDFILE <MSG> chore(.gitignore): ignore some common files <DFF> @@ -0,0 +1,7 @@ +*.html.js +.DS_Store +.grunt +/node_modules +/dist +*-SNAPSHOT* +
7
chore(.gitignore): ignore some common files
0
gitignore
mit
Semantic-Org/Semantic-UI-Angular
10072323
<NME> CHANGELOG.md <BEF> ## 4.0.1 (December 30th, 2021) Bugfixes: - ab_test must return metadata on error or if split is disabled/excluded user (@andrehjr, #622) - Fix versioned experiments when used with allow_multiple_experiments=control (@andrehjr, #613) - Only block Pinterest bot (@huoxito, #606) - Respect experiment defaults when loading experiments in initializer. (@mattwd7, #599) - Removes metadata key when it updated to nil (@andrehjr, #633) Features: - Make goals accessible via on_trial_complete callbacks (@robin-phung, #625) - Make goals accessible via on_trial_complete callbacks (@robin-phung, #625) - Replace usage of SimpleRandom with RubyStats(Used for Beta Distribution RNG) (@andrehjr, #616) - Introduce enable/disable experiment cohorting (@robin-phung, #615) - Add on_experiment_winner_choose callback (@GenaMinenkov, #574) - Add Split::Cache to reduce load on Redis (@rdh, #648) - Caching based optimization in the experiment#save path (@amangup, #652) - Adds config option for cookie domain (@joedelia, #664) Misc: - Drop support for Ruby < 2.5 (@andrehjr, #627) - Drop support for Rails < 5 (@andrehjr, #607) - Bump minimum required redis to 4.2 (@andrehjr, #628) - Removed repeated loading from config (@robin-phung, #619) - Simplify RedisInterface usage when persisting Experiment alternatives (@andrehjr, #632) - Remove redis_url impl. Deprecated on version 2.2 (@andrehjr, #631) - Remove thread_safe config as redis-rb is thread_safe by default (@andrehjr, #630) - Fix typo of in `Split::Trial` class variable (TomasBarry, #644) - Single HSET to update values, instead of multiple ones (@andrehjr, #640) - Use Redis#hmset to keep compatibility with Redis < 4.0 (@andrehjr, #659) - Remove 'set' parsing for alternatives. Sets were used as storage and deprecated on 0.x (@andrehjr, #639) - Adding documentation related to what is stored on cookies. (@andrehjr, #634) - Keep railtie defined under the Split gem namespace (@avit, #666) - Update RSpec helper to support block syntax (@clowder, #665) ## 3.4.1 (November 12th, 2019) Bugfixes: - Reference ActionController directly when including split helpers, to avoid breaking Rails API Controllers (@andrehjr, #602) ## 3.4.0 (November 9th, 2019) Features: - Improve DualAdapter (@santib, #588), adds a new configuration for the DualAdapter, making it possible to keep consistency for logged_out/logged_in users. It's a opt-in flag. No Behavior was changed on this release. - Make dashboard pagination default "per" param configurable (@alopatin, #597) Bugfixes: - Fix `force_alternative` for experiments with incremented version (@giraffate, #568) - Persist alternative weights (@giraffate, #570) - Combined experiment performance improvements (@gnanou, #575) - Handle correctly case when ab_finished is called before ab_test for a user (@gnanou, #577) - When loading active_experiments, it should not look into user's 'finished' keys (@andrehjr, #582) Misc: - Remove `rubyforge_project` from gemspec (@giraffate, #583) - Fix URLs to replace http with https (@giraffate , #584) - Lazily include split helpers in ActionController::Base (@hasghari, #586) - Fix unused variable warnings (@andrehjr, #592) - Fix ruby warnings (@andrehjr, #593) - Update rubocop.yml config (@andrehjr, #594) - Add frozen_string_literal to all files that were missing it (@andrehjr, #595) ## 3.3.2 (April 12th, 2019) Features: - Added uptime robot to configuration.rb (@razel1982, #556) - Check to see if being run in Rails application and run in before_initialize (@husteadrobert, #555) Bugfixes: - Fix error message interpolation (@hanibash, #553) - Fix Bigdecimal warnings (@agraves, #551) - Avoid hitting up on redis for robots/excluded users. (@andrehjr, #544) - Checks for defined?(request) on Helper#exclude_visitor?. (@andrehjr) Misc: - Update travis to add Rails 6 (@edmilton, #559) - Fix broken specs in developement environment (@dougpetronilio, #557) ## 3.3.1 (January 11th, 2019) Features: - Filter some more bots (@janosch-x, #542) Bugfixes: - Fix Dashboard Pagination Helper typo (@cattekin, #541) - Do not storage alternative in cookie if experiment has a winner (@sadhu89, #539) - fix user participating alternative not found (@NaturalHokke, #536) Misc: - Tweak RSpec instructions (@eliotsykes, #540) - Improve README regarding rspec usage (@vermaxik, #538) ## 3.3.0 (August 13th, 2018) Features: - Added pagination for dashboard (@GeorgeGorbanev, #518) - Add Facebot crawler to list of bots (@pfeiffer, #530) - Ignore previewing requests (@pfeiffer, #531) - Fix binding of ignore_filter (@pfeiffer, #533) Bugfixes: - Fix cookie header duplication (@andrehjr, #522) Performance: - Improve performance of RedisInterface#make_list_length by using LTRIM command (@mlovic, #509) Misc: - Update development dependencies - test rails 5.2 on travis (@lostapathy, #524) - update ruby versions for travis (@lostapathy, #525) ## 3.2.0 (September 21st, 2017) Features: - Allow configuration of how often winning alternatives are recalculated (@patbl, #501) Bugfixes: - Avoid z_score numeric exception for conversion rates >1 (@cmantas, #503) - Fix combined experiments (@semanticart, #502) ## 3.1.1 (August 30th, 2017) Bugfixes: - Bring back support for ruby 1.9.3 and greater (rubygems 2.0.0 or greater now required) (@patbl, #498) Misc: - Document testing with RSpec (@eliotsykes, #495) ## 3.1.0 (August 14th, 2017) Features: - Support for combined experiments (@daviddening, #493) - Rewrite CookieAdapter to work with Rack::Request and Rack::Response directly (@andrehjr, #490) - Enumeration of a User's Experiments that Respects the db_failover Option(@MarkRoddy, #487) Bugfixes: - Blocked a few more common bot user agents (@kylerippey, #485) Misc: - Repository Audit by Maintainer.io (@RichardLitt, #484) - Update development dependencies - Test on ruby 2.4.1 - Test compatibility with rails 5.1 - Add uris to metadata section in gemspec ## 3.0.0 (March 30th, 2017) Features: - added block randomization algorithm and specs (@hulleywood, #475) - Add ab_record_extra_info to allow record extra info to alternative and display on dashboard. (@tranngocsam, #460) Bugfixes: - Avoid crashing on Ruby 2.4 for numeric strings (@flori, #470) - Fix issue where redis isn't required (@tomciopp , #466) Misc: - Avoid variable_size_secure_compare private method (@eliotsykes, #465) ## 2.2.0 (November 11th, 2016) **Backwards incompatible!** Redis keys are renamed. Please make sure all running tests are completed before you upgrade, as they will reset. Features: - Remove dependency on Redis::Namespace (@bschaeffer, #425) - Make resetting on experiment change optional (@moggyboy, #430) - Add ability to force alternative on dashboard (@ccallebs, #437) Bugfixes: - Fix variations reset across page loads for multiple=control and improve coverage (@Vasfed, #432) Misc: - Remove Explicit Return (@BradHudson, #441) - Update Redis config docs (@bschaeffer, #422) - Harden HTTP Basic snippet against timing attacks (@eliotsykes, #443) - Removed a couple old ruby 1.8 hacks (@andrew, #456) - Run tests on rails 5 (@andrew, #457) - Fixed a few codeclimate warnings (@andrew, #458) - Use codeclimate for test coverage (@andrew #455) ## 2.1.0 (August 8th, 2016) Features: - Support REDIS_PROVIDER variable used in Heroku (@kartikluke, #426) ## 2.0.0 (July 17th, 2016) Breaking changes: - Removed deprecated `finished` and `begin_experiment` methods - Namespaced override param to avoid potential clashes (@henrik, #398) ## 1.7.0 (June 28th, 2016) Features: - Running concurrent experiments on same endpoint/view (@karmakaze, #421) ## 1.6.0 (June 16th, 2016) Features: - Add Dual Redis(logged-in)/cookie(logged-out) persistence adapter (@karmakaze, #420) ## 1.5.0 (June 8th, 2016) Features: - Add `expire_seconds:` TTL option to RedisAdapter (@karmakaze, #409) - Optional custom persistence adapter (@ndelage, #411) Misc: - Use fakeredis for testing (@andrew, #412) ## 1.4.5 (June 7th, 2016) Bugfixes: - FIX Negative numbers on non-finished (@divineforest, #408) - Eliminate extra RedisAdapter hget (@karmakaze, #407) - Remove unecessary code from Experiment class (@pakallis, #391, #392, #393) Misc: - Simplify Configuration#normalized_experiments (@pakallis, #395) - Clarify test running instructions (@henrik, #397) ## 1.4.4 (May 9th, 2016) Bugfixes: - Increment participation if store override is true and no experiment key exists (@spheric, #380) Misc: - Deprecated `finished` method in favour of `ab_finished` (@andreibondarev, #389) - Added minimum version requirement to simple-random - Clarify finished with first option being a hash in Readme (@henrik, #382) - Refactoring the User abstraction (@andreibondarev, #384) ## 1.4.3 (April 28th, 2016) Features: - add on_trial callback whenever a trial is started (@mtyeh411, #375) Bugfixes: - Allow algorithm configuration at experiment level (@007sumit, #376) Misc: - only choose override if it exists as valid alternative (@spheric, #377) ## 1.4.2 (April 25th, 2016) Misc: - Deprecated some legacy methods (@andreibondarev, #374) ## 1.4.1 (April 21st, 2016) Bugfixes: - respect manual start configuration after an experiment has been deleted (@mtyeh411, #372) Misc: - Introduce goals collection to reduce complexity of Experiment#save (@pakallis, #365) - Revise specs according to http://betterspecs.org/ (@hkliya, #369) ## 1.4.0 (April 2nd, 2016) Features: - Added experiment filters to dashboard (@ccallebs, #363, #364) - Added Contributor Covenant Code of Conduct ## 1.3.2 (January 2nd, 2016) Bugfixes: - Fix deleting experiments in from the updated dashboard (@craigmcnamara, #352) ## 1.3.1 (January 1st, 2016) Bugfixes: - Fix the dashboard for experiments with ‘/‘ in the name. (@craigmcnamara, #349) ## 1.3.0 (October 20th, 2015) Features: - allow for custom redis_url different from ENV variable (@davidgrieser, #323) - add ability to change the length of the persistence cookie (@peterylai, #335) Bugfixes: - Rescue from Redis::BaseError instead of Redis::CannotConnectError (@nfm, #342) - Fix active experiments when experiment is on a later version (@ndrisso, #331) - Fix caching of winning alternative (@nfm, #329) Misc: - Remove duplication from Experiment#save (@pakallis, #333) - Remove unnecessary argument from Experiment#write_to_alternative (@t4deu, #332) ## 1.2.1 (May 17th, 2015) Features: - Handle redis DNS resolution failures gracefully (@fusion2004, #310) - Push metadata to ab_test block (@ekorneeff, #296) - Helper methods are now private when included in controllers (@ipoval, #303) Bugfixes: - Return an empty hash as metadata when Split is disabled (@tomasdundacek, #313) - Don't use capture helper from ActionView (@tomasdundacek, #312) Misc: - Remove body "max-width" from dashboard (@xicreative, #299) - fix private for class methods (@ipoval, #301) - minor memoization fix in spec (@ipoval, #304) - Minor documentation fixes (#295, #297, #305, #308) ## 1.2.0 (January 24th, 2015) Features: - Configure redis using environment variables if available (@saratovsource , #293) - Store metadata on experiment configuration (@dekz, #291) Bugfixes: - Revert the Trial#complete! public API to support noargs (@dekz, #292) ## 1.1.0 (January 9th, 2015) Changes: - Public class methods on `Split::Experiment` (e.g., `find_or_create`) have been moved to `Split::ExperimentCatalog`. Features: - Decouple trial from Split::Helper (@joshdover, #286) - Helper method for Active Experiments (@blahblahblah-, #273) Misc: - Use the new travis container based infrastructure for tests (@andrew, #280) ## 1.0.0 (October 12th, 2014) Changes: - Remove support for Ruby 1.8.7 and Rails 2.3 (@qpowell, #271) ## 0.8.0 (September 25th, 2014) Features: - Added new way to calculate the probability an alternative is the winner (@caser, #266, #251) - support multiple metrics per experiment (@stevenou, #260) Bugfixes: - Avoiding call to params in EncapsulatedHelper (@afn, #257) ## 0.7.3 (September 16th, 2014) Features: - Disable all split tests via a URL parameter (@hwartig, #263) Bugfixes: - Correctly escape experiment names on dashboard (@ecaron, #265) - Handle redis connection exception error properly (@andrew, #245) ## 0.7.2 (June 12th, 2014) Features: - Show metrics on the dashboard (@swrobel, #241) Bugfixes: - Avoid nil error with ExperimentCatalog when upgrading (@danielschwartz, #253) - [SECURITY ISSUE] Only allow known alternatives as query param overrides (@ankane, #255) ## 0.7.1 (March 20th, 2014) Features: - You can now reopen experiment from the dashboard (@mikezaby, #235) Misc: - Internal code tidy up (@IanVaughan, #238) ## 0.7.0 (December 26th, 2013) Features: - Significantly improved z-score algorithm (@caser ,#221) - Better sorting of Experiments on dashboard (@wadako111, #218) Bugfixes: - Fixed start button not being displayed in some cases (@vigosan, #219) Misc: - Experiment#initialize refactoring (@nberger, #224) - Extract ExperimentStore into a seperate class (@nberger, #225) ## 0.6.6 (October 15th, 2013) Features: - Sort experiments on Dashboard so "active" ones without a winner appear first (@swrobel, #204) - Starting tests manually (@duksis, #209) Bugfixes: - Only trigger completion callback with valid Trial (@segfaultAX, #208) - Fixed bug with `resettable` when using `normalize_experiments` (@jonashuckestein, #213) Misc: - Added more bots to filter list (@lbeder, #214, #215, #216) ## 0.6.5 (August 23, 2013) Features: - Added Redis adapter for persisting experiments across sessions (@fengb, #203) Misc: - Expand upon algorithms section in README (@swrobel, #200) ## 0.6.4 (August 8, 2013) Features: - Add hooks for experiment deletion and resetting (@craigmcnamara, #198) - Allow Split::Helper to be used outside of a controller (@nfm, #190) - Show current Rails/Rack Env in dashboard (@rceee, #187) Bugfixes: - Fix whiplash algorithm when using goals (@swrobel, #193) Misc: - Refactor dashboard js (@buddhamagnet) ## 0.6.3 (July 8, 2013) Features: - Add hooks for Trial#choose! and Trial#complete! (@bmarini, #176) Bugfixes: - Stores and parses Experiment's start_time as a UNIX integer (@joeroot, #177) ## 0.6.2 (June 6, 2013) Features: - Rails 2.3 compatibility (@bhcarpenter, #167) - Adding possibility to store overridden alternative (@duksis, #173) Misc: - Now testing against multiple versions of rails ## 0.6.1 (May 4, 2013) Bugfixes: - Use the specified algorithm for the experiment instead of the default (@woodhull, #165) Misc: - Ensure experiements are valid when configuring (@ashmckenzie, #159) - Allow arrays to be passed to ab_test (@fenelon, #156) ## 0.6.0 (April 4, 2013) Features: - Support for Ruby 2.0.0 (@phoet, #142) - Multiple Goals (@liujin, #109) - Ignoring IPs using Regular Expressions (@waynemoore, #119) - Added ability to add more bots to the default list (@themgt, #140) - Allow custom configuration of user blocking logic (@phoet , #148) Bugfixes: - Fixed regression in handling of config files (@iangreenleaf, #115) - Fixed completion rate increases for experiments users aren't participating in (@philnash, #67) - Handle exceptions from invalid JSON in cookies (@iangreenleaf, #126) Misc: - updated minimum json version requirement - Refactor Yaml Configuration (@rtwomey, #124) - Refactoring of Experiments (@iangreenleaf @tamird, #117 #118) - Added more known Bots, including Pingdom, Bing, YandexBot (@julesie, @zinkkrysty, @dimko) - Improved Readme (@iangreenleaf @phoet) ## 0.5.0 (January 28, 2013) Features: - Persistence Adapters: Cookies and Session (@patbenatar, #98) - Configure experiments from a hash (@iangreenleaf, #97) - Pluggable sampling algorithms (@woodhull, #105) Bugfixes: - Fixed negative number of non-finished rates (@philnash, #83) - Fixed behaviour of finished(:reset => false) (@philnash, #88) - Only take into consideration positive z-scores (@thomasmaas, #96) - Amended ab_test method to raise ArgumentError if passed integers or symbols as alternatives (@buddhamagnet, #81) ## 0.4.6 (October 28, 2012) Features: - General code quality improvements (@buddhamagnet, #79) Bugfixes: - Don't increment the experiment counter if user has finished (@dimko, #78) - Fixed an incorrect test (@jaywengrow, #74) ## 0.4.5 (August 30, 2012) Bugfixes: - Fixed header gradient in FF/Opera (@philnash, #69) - Fixed reseting of experiment in session (@apsoto, #43) ## 0.4.4 (August 9, 2012) Features: - Allow parameter overrides, even without Redis. (@bhcarpenter, #62) Bugfixes: - Fixes version number always increasing when alternatives are changed (@philnash, #63) - updated guard-rspec to version 1.2 ## 0.4.3 (July 8, 2012) Features: - redis failover now recovers from all redis-related exceptions ## 0.4.2 (June 1, 2012) Features: - Now works with v3.0 of redis gem Bugfixes: - Fixed redis failover on Rubinius ## 0.4.1 (April 6, 2012) Features: - Added configuration option to disable Split testing (@ilyakatz, #45) Bugfixes: - Fix weights for existing experiments (@andreas, #40) - Fixed dashboard range error (@andrew, #42) ## 0.4.0 (March 7, 2012) **IMPORTANT** If using ruby 1.8.x and weighted alternatives you should always pass the control alternative through as the second argument with any other alternatives as a third argument because the order of the hash is not preserved in ruby 1.8, ruby 1.9 users are not affected by this bug. Features: - Experiments now record when they were started (@vrish88, #35) - Old versions of experiments in sessions are now cleaned up - Avoid users participating in multiple experiments at once (#21) Bugfixes: - Overriding alternatives doesn't work for weighted alternatives (@layflags, #34) - confidence_level helper should handle tiny z-scores (#23) ## 0.3.3 (February 16, 2012) Bugfixes: - Fixed redis failover when a block was passed to ab_test (@layflags, #33) ## 0.3.2 (February 12, 2012) Features: - Handle redis errors gracefully (@layflags, #32) ## 0.3.1 (November 19, 2011) Features: - General code tidy up (@ryanlecompte, #22, @mocoso, #28) - Lazy loading data from Redis (@lautis, #25) Bugfixes: - Handle unstarted experiments (@mocoso, #27) - Relaxed Sinatra version requirement (@martinclu, #24) ## 0.3.0 (October 9, 2011) Features: - Redesigned dashboard (@mrappleton, #17) - Use atomic increments in redis for better concurrency (@lautis, #18) - Weighted alternatives Bugfixes: - Fix to allow overriding of experiments that aren't on version 1 ## 0.2.4 (July 18, 2011) Features: - Added option to finished to not reset the users session Bugfixes: - Only allow strings as alternatives, fixes strange errors when passing true/false or symbols ## 0.2.3 (June 26, 2011) Features: - Experiments can now be deleted from the dashboard - ab_test helper now accepts a block - Improved dashboard Bugfixes: - After resetting an experiment, existing users of that experiment will also be reset ## 0.2.2 (June 11, 2011) Features: - Updated redis-namespace requirement to 1.0.3 - Added a configuration object for changing options - Robot regex can now be changed via a configuration options - Added ability to ignore visits from specified IP addresses - Dashboard now shows percentage improvement of alternatives compared to the control - If the alternatives of an experiment are changed it resets the experiment and uses the new alternatives Bugfixes: - Saving an experiment multiple times no longer creates duplicate alternatives ## 0.2.1 (May 29, 2011) Bugfixes: - Convert legacy sets to lists to avoid exceptions during upgrades from 0.1.x ## 0.2.0 (May 29, 2011) Features: - Override an alternative via a url parameter - Experiments can now be reset from the dashboard - The first alternative is now considered the control - General dashboard usability improvements - Robots are ignored and given the control alternative Bugfixes: - Alternatives are now store in a list rather than a set to ensure consistent ordering - Fixed diving by zero errors ## 0.1.1 (May 18, 2011) Bugfixes: - More Robust conversion rate display on dashboard - Ensure `Split::Version` is available everywhere, fixed dashboard ## 0.1.0 (May 17, 2011) Initial Release <MSG> Add missing entry to the changelog <DFF> @@ -6,6 +6,7 @@ Bugfixes: - Only block Pinterest bot (@huoxito, #606) - Respect experiment defaults when loading experiments in initializer. (@mattwd7, #599) - Removes metadata key when it updated to nil (@andrehjr, #633) +- Force experiment does not count for metrics (@andrehjr, #637) Features: - Make goals accessible via on_trial_complete callbacks (@robin-phung, #625)
1
Add missing entry to the changelog
0
.md
md
mit
splitrb/split
10072324
<NME> CHANGELOG.md <BEF> ## 4.0.1 (December 30th, 2021) Bugfixes: - ab_test must return metadata on error or if split is disabled/excluded user (@andrehjr, #622) - Fix versioned experiments when used with allow_multiple_experiments=control (@andrehjr, #613) - Only block Pinterest bot (@huoxito, #606) - Respect experiment defaults when loading experiments in initializer. (@mattwd7, #599) - Removes metadata key when it updated to nil (@andrehjr, #633) Features: - Make goals accessible via on_trial_complete callbacks (@robin-phung, #625) - Make goals accessible via on_trial_complete callbacks (@robin-phung, #625) - Replace usage of SimpleRandom with RubyStats(Used for Beta Distribution RNG) (@andrehjr, #616) - Introduce enable/disable experiment cohorting (@robin-phung, #615) - Add on_experiment_winner_choose callback (@GenaMinenkov, #574) - Add Split::Cache to reduce load on Redis (@rdh, #648) - Caching based optimization in the experiment#save path (@amangup, #652) - Adds config option for cookie domain (@joedelia, #664) Misc: - Drop support for Ruby < 2.5 (@andrehjr, #627) - Drop support for Rails < 5 (@andrehjr, #607) - Bump minimum required redis to 4.2 (@andrehjr, #628) - Removed repeated loading from config (@robin-phung, #619) - Simplify RedisInterface usage when persisting Experiment alternatives (@andrehjr, #632) - Remove redis_url impl. Deprecated on version 2.2 (@andrehjr, #631) - Remove thread_safe config as redis-rb is thread_safe by default (@andrehjr, #630) - Fix typo of in `Split::Trial` class variable (TomasBarry, #644) - Single HSET to update values, instead of multiple ones (@andrehjr, #640) - Use Redis#hmset to keep compatibility with Redis < 4.0 (@andrehjr, #659) - Remove 'set' parsing for alternatives. Sets were used as storage and deprecated on 0.x (@andrehjr, #639) - Adding documentation related to what is stored on cookies. (@andrehjr, #634) - Keep railtie defined under the Split gem namespace (@avit, #666) - Update RSpec helper to support block syntax (@clowder, #665) ## 3.4.1 (November 12th, 2019) Bugfixes: - Reference ActionController directly when including split helpers, to avoid breaking Rails API Controllers (@andrehjr, #602) ## 3.4.0 (November 9th, 2019) Features: - Improve DualAdapter (@santib, #588), adds a new configuration for the DualAdapter, making it possible to keep consistency for logged_out/logged_in users. It's a opt-in flag. No Behavior was changed on this release. - Make dashboard pagination default "per" param configurable (@alopatin, #597) Bugfixes: - Fix `force_alternative` for experiments with incremented version (@giraffate, #568) - Persist alternative weights (@giraffate, #570) - Combined experiment performance improvements (@gnanou, #575) - Handle correctly case when ab_finished is called before ab_test for a user (@gnanou, #577) - When loading active_experiments, it should not look into user's 'finished' keys (@andrehjr, #582) Misc: - Remove `rubyforge_project` from gemspec (@giraffate, #583) - Fix URLs to replace http with https (@giraffate , #584) - Lazily include split helpers in ActionController::Base (@hasghari, #586) - Fix unused variable warnings (@andrehjr, #592) - Fix ruby warnings (@andrehjr, #593) - Update rubocop.yml config (@andrehjr, #594) - Add frozen_string_literal to all files that were missing it (@andrehjr, #595) ## 3.3.2 (April 12th, 2019) Features: - Added uptime robot to configuration.rb (@razel1982, #556) - Check to see if being run in Rails application and run in before_initialize (@husteadrobert, #555) Bugfixes: - Fix error message interpolation (@hanibash, #553) - Fix Bigdecimal warnings (@agraves, #551) - Avoid hitting up on redis for robots/excluded users. (@andrehjr, #544) - Checks for defined?(request) on Helper#exclude_visitor?. (@andrehjr) Misc: - Update travis to add Rails 6 (@edmilton, #559) - Fix broken specs in developement environment (@dougpetronilio, #557) ## 3.3.1 (January 11th, 2019) Features: - Filter some more bots (@janosch-x, #542) Bugfixes: - Fix Dashboard Pagination Helper typo (@cattekin, #541) - Do not storage alternative in cookie if experiment has a winner (@sadhu89, #539) - fix user participating alternative not found (@NaturalHokke, #536) Misc: - Tweak RSpec instructions (@eliotsykes, #540) - Improve README regarding rspec usage (@vermaxik, #538) ## 3.3.0 (August 13th, 2018) Features: - Added pagination for dashboard (@GeorgeGorbanev, #518) - Add Facebot crawler to list of bots (@pfeiffer, #530) - Ignore previewing requests (@pfeiffer, #531) - Fix binding of ignore_filter (@pfeiffer, #533) Bugfixes: - Fix cookie header duplication (@andrehjr, #522) Performance: - Improve performance of RedisInterface#make_list_length by using LTRIM command (@mlovic, #509) Misc: - Update development dependencies - test rails 5.2 on travis (@lostapathy, #524) - update ruby versions for travis (@lostapathy, #525) ## 3.2.0 (September 21st, 2017) Features: - Allow configuration of how often winning alternatives are recalculated (@patbl, #501) Bugfixes: - Avoid z_score numeric exception for conversion rates >1 (@cmantas, #503) - Fix combined experiments (@semanticart, #502) ## 3.1.1 (August 30th, 2017) Bugfixes: - Bring back support for ruby 1.9.3 and greater (rubygems 2.0.0 or greater now required) (@patbl, #498) Misc: - Document testing with RSpec (@eliotsykes, #495) ## 3.1.0 (August 14th, 2017) Features: - Support for combined experiments (@daviddening, #493) - Rewrite CookieAdapter to work with Rack::Request and Rack::Response directly (@andrehjr, #490) - Enumeration of a User's Experiments that Respects the db_failover Option(@MarkRoddy, #487) Bugfixes: - Blocked a few more common bot user agents (@kylerippey, #485) Misc: - Repository Audit by Maintainer.io (@RichardLitt, #484) - Update development dependencies - Test on ruby 2.4.1 - Test compatibility with rails 5.1 - Add uris to metadata section in gemspec ## 3.0.0 (March 30th, 2017) Features: - added block randomization algorithm and specs (@hulleywood, #475) - Add ab_record_extra_info to allow record extra info to alternative and display on dashboard. (@tranngocsam, #460) Bugfixes: - Avoid crashing on Ruby 2.4 for numeric strings (@flori, #470) - Fix issue where redis isn't required (@tomciopp , #466) Misc: - Avoid variable_size_secure_compare private method (@eliotsykes, #465) ## 2.2.0 (November 11th, 2016) **Backwards incompatible!** Redis keys are renamed. Please make sure all running tests are completed before you upgrade, as they will reset. Features: - Remove dependency on Redis::Namespace (@bschaeffer, #425) - Make resetting on experiment change optional (@moggyboy, #430) - Add ability to force alternative on dashboard (@ccallebs, #437) Bugfixes: - Fix variations reset across page loads for multiple=control and improve coverage (@Vasfed, #432) Misc: - Remove Explicit Return (@BradHudson, #441) - Update Redis config docs (@bschaeffer, #422) - Harden HTTP Basic snippet against timing attacks (@eliotsykes, #443) - Removed a couple old ruby 1.8 hacks (@andrew, #456) - Run tests on rails 5 (@andrew, #457) - Fixed a few codeclimate warnings (@andrew, #458) - Use codeclimate for test coverage (@andrew #455) ## 2.1.0 (August 8th, 2016) Features: - Support REDIS_PROVIDER variable used in Heroku (@kartikluke, #426) ## 2.0.0 (July 17th, 2016) Breaking changes: - Removed deprecated `finished` and `begin_experiment` methods - Namespaced override param to avoid potential clashes (@henrik, #398) ## 1.7.0 (June 28th, 2016) Features: - Running concurrent experiments on same endpoint/view (@karmakaze, #421) ## 1.6.0 (June 16th, 2016) Features: - Add Dual Redis(logged-in)/cookie(logged-out) persistence adapter (@karmakaze, #420) ## 1.5.0 (June 8th, 2016) Features: - Add `expire_seconds:` TTL option to RedisAdapter (@karmakaze, #409) - Optional custom persistence adapter (@ndelage, #411) Misc: - Use fakeredis for testing (@andrew, #412) ## 1.4.5 (June 7th, 2016) Bugfixes: - FIX Negative numbers on non-finished (@divineforest, #408) - Eliminate extra RedisAdapter hget (@karmakaze, #407) - Remove unecessary code from Experiment class (@pakallis, #391, #392, #393) Misc: - Simplify Configuration#normalized_experiments (@pakallis, #395) - Clarify test running instructions (@henrik, #397) ## 1.4.4 (May 9th, 2016) Bugfixes: - Increment participation if store override is true and no experiment key exists (@spheric, #380) Misc: - Deprecated `finished` method in favour of `ab_finished` (@andreibondarev, #389) - Added minimum version requirement to simple-random - Clarify finished with first option being a hash in Readme (@henrik, #382) - Refactoring the User abstraction (@andreibondarev, #384) ## 1.4.3 (April 28th, 2016) Features: - add on_trial callback whenever a trial is started (@mtyeh411, #375) Bugfixes: - Allow algorithm configuration at experiment level (@007sumit, #376) Misc: - only choose override if it exists as valid alternative (@spheric, #377) ## 1.4.2 (April 25th, 2016) Misc: - Deprecated some legacy methods (@andreibondarev, #374) ## 1.4.1 (April 21st, 2016) Bugfixes: - respect manual start configuration after an experiment has been deleted (@mtyeh411, #372) Misc: - Introduce goals collection to reduce complexity of Experiment#save (@pakallis, #365) - Revise specs according to http://betterspecs.org/ (@hkliya, #369) ## 1.4.0 (April 2nd, 2016) Features: - Added experiment filters to dashboard (@ccallebs, #363, #364) - Added Contributor Covenant Code of Conduct ## 1.3.2 (January 2nd, 2016) Bugfixes: - Fix deleting experiments in from the updated dashboard (@craigmcnamara, #352) ## 1.3.1 (January 1st, 2016) Bugfixes: - Fix the dashboard for experiments with ‘/‘ in the name. (@craigmcnamara, #349) ## 1.3.0 (October 20th, 2015) Features: - allow for custom redis_url different from ENV variable (@davidgrieser, #323) - add ability to change the length of the persistence cookie (@peterylai, #335) Bugfixes: - Rescue from Redis::BaseError instead of Redis::CannotConnectError (@nfm, #342) - Fix active experiments when experiment is on a later version (@ndrisso, #331) - Fix caching of winning alternative (@nfm, #329) Misc: - Remove duplication from Experiment#save (@pakallis, #333) - Remove unnecessary argument from Experiment#write_to_alternative (@t4deu, #332) ## 1.2.1 (May 17th, 2015) Features: - Handle redis DNS resolution failures gracefully (@fusion2004, #310) - Push metadata to ab_test block (@ekorneeff, #296) - Helper methods are now private when included in controllers (@ipoval, #303) Bugfixes: - Return an empty hash as metadata when Split is disabled (@tomasdundacek, #313) - Don't use capture helper from ActionView (@tomasdundacek, #312) Misc: - Remove body "max-width" from dashboard (@xicreative, #299) - fix private for class methods (@ipoval, #301) - minor memoization fix in spec (@ipoval, #304) - Minor documentation fixes (#295, #297, #305, #308) ## 1.2.0 (January 24th, 2015) Features: - Configure redis using environment variables if available (@saratovsource , #293) - Store metadata on experiment configuration (@dekz, #291) Bugfixes: - Revert the Trial#complete! public API to support noargs (@dekz, #292) ## 1.1.0 (January 9th, 2015) Changes: - Public class methods on `Split::Experiment` (e.g., `find_or_create`) have been moved to `Split::ExperimentCatalog`. Features: - Decouple trial from Split::Helper (@joshdover, #286) - Helper method for Active Experiments (@blahblahblah-, #273) Misc: - Use the new travis container based infrastructure for tests (@andrew, #280) ## 1.0.0 (October 12th, 2014) Changes: - Remove support for Ruby 1.8.7 and Rails 2.3 (@qpowell, #271) ## 0.8.0 (September 25th, 2014) Features: - Added new way to calculate the probability an alternative is the winner (@caser, #266, #251) - support multiple metrics per experiment (@stevenou, #260) Bugfixes: - Avoiding call to params in EncapsulatedHelper (@afn, #257) ## 0.7.3 (September 16th, 2014) Features: - Disable all split tests via a URL parameter (@hwartig, #263) Bugfixes: - Correctly escape experiment names on dashboard (@ecaron, #265) - Handle redis connection exception error properly (@andrew, #245) ## 0.7.2 (June 12th, 2014) Features: - Show metrics on the dashboard (@swrobel, #241) Bugfixes: - Avoid nil error with ExperimentCatalog when upgrading (@danielschwartz, #253) - [SECURITY ISSUE] Only allow known alternatives as query param overrides (@ankane, #255) ## 0.7.1 (March 20th, 2014) Features: - You can now reopen experiment from the dashboard (@mikezaby, #235) Misc: - Internal code tidy up (@IanVaughan, #238) ## 0.7.0 (December 26th, 2013) Features: - Significantly improved z-score algorithm (@caser ,#221) - Better sorting of Experiments on dashboard (@wadako111, #218) Bugfixes: - Fixed start button not being displayed in some cases (@vigosan, #219) Misc: - Experiment#initialize refactoring (@nberger, #224) - Extract ExperimentStore into a seperate class (@nberger, #225) ## 0.6.6 (October 15th, 2013) Features: - Sort experiments on Dashboard so "active" ones without a winner appear first (@swrobel, #204) - Starting tests manually (@duksis, #209) Bugfixes: - Only trigger completion callback with valid Trial (@segfaultAX, #208) - Fixed bug with `resettable` when using `normalize_experiments` (@jonashuckestein, #213) Misc: - Added more bots to filter list (@lbeder, #214, #215, #216) ## 0.6.5 (August 23, 2013) Features: - Added Redis adapter for persisting experiments across sessions (@fengb, #203) Misc: - Expand upon algorithms section in README (@swrobel, #200) ## 0.6.4 (August 8, 2013) Features: - Add hooks for experiment deletion and resetting (@craigmcnamara, #198) - Allow Split::Helper to be used outside of a controller (@nfm, #190) - Show current Rails/Rack Env in dashboard (@rceee, #187) Bugfixes: - Fix whiplash algorithm when using goals (@swrobel, #193) Misc: - Refactor dashboard js (@buddhamagnet) ## 0.6.3 (July 8, 2013) Features: - Add hooks for Trial#choose! and Trial#complete! (@bmarini, #176) Bugfixes: - Stores and parses Experiment's start_time as a UNIX integer (@joeroot, #177) ## 0.6.2 (June 6, 2013) Features: - Rails 2.3 compatibility (@bhcarpenter, #167) - Adding possibility to store overridden alternative (@duksis, #173) Misc: - Now testing against multiple versions of rails ## 0.6.1 (May 4, 2013) Bugfixes: - Use the specified algorithm for the experiment instead of the default (@woodhull, #165) Misc: - Ensure experiements are valid when configuring (@ashmckenzie, #159) - Allow arrays to be passed to ab_test (@fenelon, #156) ## 0.6.0 (April 4, 2013) Features: - Support for Ruby 2.0.0 (@phoet, #142) - Multiple Goals (@liujin, #109) - Ignoring IPs using Regular Expressions (@waynemoore, #119) - Added ability to add more bots to the default list (@themgt, #140) - Allow custom configuration of user blocking logic (@phoet , #148) Bugfixes: - Fixed regression in handling of config files (@iangreenleaf, #115) - Fixed completion rate increases for experiments users aren't participating in (@philnash, #67) - Handle exceptions from invalid JSON in cookies (@iangreenleaf, #126) Misc: - updated minimum json version requirement - Refactor Yaml Configuration (@rtwomey, #124) - Refactoring of Experiments (@iangreenleaf @tamird, #117 #118) - Added more known Bots, including Pingdom, Bing, YandexBot (@julesie, @zinkkrysty, @dimko) - Improved Readme (@iangreenleaf @phoet) ## 0.5.0 (January 28, 2013) Features: - Persistence Adapters: Cookies and Session (@patbenatar, #98) - Configure experiments from a hash (@iangreenleaf, #97) - Pluggable sampling algorithms (@woodhull, #105) Bugfixes: - Fixed negative number of non-finished rates (@philnash, #83) - Fixed behaviour of finished(:reset => false) (@philnash, #88) - Only take into consideration positive z-scores (@thomasmaas, #96) - Amended ab_test method to raise ArgumentError if passed integers or symbols as alternatives (@buddhamagnet, #81) ## 0.4.6 (October 28, 2012) Features: - General code quality improvements (@buddhamagnet, #79) Bugfixes: - Don't increment the experiment counter if user has finished (@dimko, #78) - Fixed an incorrect test (@jaywengrow, #74) ## 0.4.5 (August 30, 2012) Bugfixes: - Fixed header gradient in FF/Opera (@philnash, #69) - Fixed reseting of experiment in session (@apsoto, #43) ## 0.4.4 (August 9, 2012) Features: - Allow parameter overrides, even without Redis. (@bhcarpenter, #62) Bugfixes: - Fixes version number always increasing when alternatives are changed (@philnash, #63) - updated guard-rspec to version 1.2 ## 0.4.3 (July 8, 2012) Features: - redis failover now recovers from all redis-related exceptions ## 0.4.2 (June 1, 2012) Features: - Now works with v3.0 of redis gem Bugfixes: - Fixed redis failover on Rubinius ## 0.4.1 (April 6, 2012) Features: - Added configuration option to disable Split testing (@ilyakatz, #45) Bugfixes: - Fix weights for existing experiments (@andreas, #40) - Fixed dashboard range error (@andrew, #42) ## 0.4.0 (March 7, 2012) **IMPORTANT** If using ruby 1.8.x and weighted alternatives you should always pass the control alternative through as the second argument with any other alternatives as a third argument because the order of the hash is not preserved in ruby 1.8, ruby 1.9 users are not affected by this bug. Features: - Experiments now record when they were started (@vrish88, #35) - Old versions of experiments in sessions are now cleaned up - Avoid users participating in multiple experiments at once (#21) Bugfixes: - Overriding alternatives doesn't work for weighted alternatives (@layflags, #34) - confidence_level helper should handle tiny z-scores (#23) ## 0.3.3 (February 16, 2012) Bugfixes: - Fixed redis failover when a block was passed to ab_test (@layflags, #33) ## 0.3.2 (February 12, 2012) Features: - Handle redis errors gracefully (@layflags, #32) ## 0.3.1 (November 19, 2011) Features: - General code tidy up (@ryanlecompte, #22, @mocoso, #28) - Lazy loading data from Redis (@lautis, #25) Bugfixes: - Handle unstarted experiments (@mocoso, #27) - Relaxed Sinatra version requirement (@martinclu, #24) ## 0.3.0 (October 9, 2011) Features: - Redesigned dashboard (@mrappleton, #17) - Use atomic increments in redis for better concurrency (@lautis, #18) - Weighted alternatives Bugfixes: - Fix to allow overriding of experiments that aren't on version 1 ## 0.2.4 (July 18, 2011) Features: - Added option to finished to not reset the users session Bugfixes: - Only allow strings as alternatives, fixes strange errors when passing true/false or symbols ## 0.2.3 (June 26, 2011) Features: - Experiments can now be deleted from the dashboard - ab_test helper now accepts a block - Improved dashboard Bugfixes: - After resetting an experiment, existing users of that experiment will also be reset ## 0.2.2 (June 11, 2011) Features: - Updated redis-namespace requirement to 1.0.3 - Added a configuration object for changing options - Robot regex can now be changed via a configuration options - Added ability to ignore visits from specified IP addresses - Dashboard now shows percentage improvement of alternatives compared to the control - If the alternatives of an experiment are changed it resets the experiment and uses the new alternatives Bugfixes: - Saving an experiment multiple times no longer creates duplicate alternatives ## 0.2.1 (May 29, 2011) Bugfixes: - Convert legacy sets to lists to avoid exceptions during upgrades from 0.1.x ## 0.2.0 (May 29, 2011) Features: - Override an alternative via a url parameter - Experiments can now be reset from the dashboard - The first alternative is now considered the control - General dashboard usability improvements - Robots are ignored and given the control alternative Bugfixes: - Alternatives are now store in a list rather than a set to ensure consistent ordering - Fixed diving by zero errors ## 0.1.1 (May 18, 2011) Bugfixes: - More Robust conversion rate display on dashboard - Ensure `Split::Version` is available everywhere, fixed dashboard ## 0.1.0 (May 17, 2011) Initial Release <MSG> Add missing entry to the changelog <DFF> @@ -6,6 +6,7 @@ Bugfixes: - Only block Pinterest bot (@huoxito, #606) - Respect experiment defaults when loading experiments in initializer. (@mattwd7, #599) - Removes metadata key when it updated to nil (@andrehjr, #633) +- Force experiment does not count for metrics (@andrehjr, #637) Features: - Make goals accessible via on_trial_complete callbacks (@robin-phung, #625)
1
Add missing entry to the changelog
0
.md
md
mit
splitrb/split
10072325
<NME> CHANGELOG.md <BEF> ## 4.0.1 (December 30th, 2021) Bugfixes: - ab_test must return metadata on error or if split is disabled/excluded user (@andrehjr, #622) - Fix versioned experiments when used with allow_multiple_experiments=control (@andrehjr, #613) - Only block Pinterest bot (@huoxito, #606) - Respect experiment defaults when loading experiments in initializer. (@mattwd7, #599) - Removes metadata key when it updated to nil (@andrehjr, #633) Features: - Make goals accessible via on_trial_complete callbacks (@robin-phung, #625) - Make goals accessible via on_trial_complete callbacks (@robin-phung, #625) - Replace usage of SimpleRandom with RubyStats(Used for Beta Distribution RNG) (@andrehjr, #616) - Introduce enable/disable experiment cohorting (@robin-phung, #615) - Add on_experiment_winner_choose callback (@GenaMinenkov, #574) - Add Split::Cache to reduce load on Redis (@rdh, #648) - Caching based optimization in the experiment#save path (@amangup, #652) - Adds config option for cookie domain (@joedelia, #664) Misc: - Drop support for Ruby < 2.5 (@andrehjr, #627) - Drop support for Rails < 5 (@andrehjr, #607) - Bump minimum required redis to 4.2 (@andrehjr, #628) - Removed repeated loading from config (@robin-phung, #619) - Simplify RedisInterface usage when persisting Experiment alternatives (@andrehjr, #632) - Remove redis_url impl. Deprecated on version 2.2 (@andrehjr, #631) - Remove thread_safe config as redis-rb is thread_safe by default (@andrehjr, #630) - Fix typo of in `Split::Trial` class variable (TomasBarry, #644) - Single HSET to update values, instead of multiple ones (@andrehjr, #640) - Use Redis#hmset to keep compatibility with Redis < 4.0 (@andrehjr, #659) - Remove 'set' parsing for alternatives. Sets were used as storage and deprecated on 0.x (@andrehjr, #639) - Adding documentation related to what is stored on cookies. (@andrehjr, #634) - Keep railtie defined under the Split gem namespace (@avit, #666) - Update RSpec helper to support block syntax (@clowder, #665) ## 3.4.1 (November 12th, 2019) Bugfixes: - Reference ActionController directly when including split helpers, to avoid breaking Rails API Controllers (@andrehjr, #602) ## 3.4.0 (November 9th, 2019) Features: - Improve DualAdapter (@santib, #588), adds a new configuration for the DualAdapter, making it possible to keep consistency for logged_out/logged_in users. It's a opt-in flag. No Behavior was changed on this release. - Make dashboard pagination default "per" param configurable (@alopatin, #597) Bugfixes: - Fix `force_alternative` for experiments with incremented version (@giraffate, #568) - Persist alternative weights (@giraffate, #570) - Combined experiment performance improvements (@gnanou, #575) - Handle correctly case when ab_finished is called before ab_test for a user (@gnanou, #577) - When loading active_experiments, it should not look into user's 'finished' keys (@andrehjr, #582) Misc: - Remove `rubyforge_project` from gemspec (@giraffate, #583) - Fix URLs to replace http with https (@giraffate , #584) - Lazily include split helpers in ActionController::Base (@hasghari, #586) - Fix unused variable warnings (@andrehjr, #592) - Fix ruby warnings (@andrehjr, #593) - Update rubocop.yml config (@andrehjr, #594) - Add frozen_string_literal to all files that were missing it (@andrehjr, #595) ## 3.3.2 (April 12th, 2019) Features: - Added uptime robot to configuration.rb (@razel1982, #556) - Check to see if being run in Rails application and run in before_initialize (@husteadrobert, #555) Bugfixes: - Fix error message interpolation (@hanibash, #553) - Fix Bigdecimal warnings (@agraves, #551) - Avoid hitting up on redis for robots/excluded users. (@andrehjr, #544) - Checks for defined?(request) on Helper#exclude_visitor?. (@andrehjr) Misc: - Update travis to add Rails 6 (@edmilton, #559) - Fix broken specs in developement environment (@dougpetronilio, #557) ## 3.3.1 (January 11th, 2019) Features: - Filter some more bots (@janosch-x, #542) Bugfixes: - Fix Dashboard Pagination Helper typo (@cattekin, #541) - Do not storage alternative in cookie if experiment has a winner (@sadhu89, #539) - fix user participating alternative not found (@NaturalHokke, #536) Misc: - Tweak RSpec instructions (@eliotsykes, #540) - Improve README regarding rspec usage (@vermaxik, #538) ## 3.3.0 (August 13th, 2018) Features: - Added pagination for dashboard (@GeorgeGorbanev, #518) - Add Facebot crawler to list of bots (@pfeiffer, #530) - Ignore previewing requests (@pfeiffer, #531) - Fix binding of ignore_filter (@pfeiffer, #533) Bugfixes: - Fix cookie header duplication (@andrehjr, #522) Performance: - Improve performance of RedisInterface#make_list_length by using LTRIM command (@mlovic, #509) Misc: - Update development dependencies - test rails 5.2 on travis (@lostapathy, #524) - update ruby versions for travis (@lostapathy, #525) ## 3.2.0 (September 21st, 2017) Features: - Allow configuration of how often winning alternatives are recalculated (@patbl, #501) Bugfixes: - Avoid z_score numeric exception for conversion rates >1 (@cmantas, #503) - Fix combined experiments (@semanticart, #502) ## 3.1.1 (August 30th, 2017) Bugfixes: - Bring back support for ruby 1.9.3 and greater (rubygems 2.0.0 or greater now required) (@patbl, #498) Misc: - Document testing with RSpec (@eliotsykes, #495) ## 3.1.0 (August 14th, 2017) Features: - Support for combined experiments (@daviddening, #493) - Rewrite CookieAdapter to work with Rack::Request and Rack::Response directly (@andrehjr, #490) - Enumeration of a User's Experiments that Respects the db_failover Option(@MarkRoddy, #487) Bugfixes: - Blocked a few more common bot user agents (@kylerippey, #485) Misc: - Repository Audit by Maintainer.io (@RichardLitt, #484) - Update development dependencies - Test on ruby 2.4.1 - Test compatibility with rails 5.1 - Add uris to metadata section in gemspec ## 3.0.0 (March 30th, 2017) Features: - added block randomization algorithm and specs (@hulleywood, #475) - Add ab_record_extra_info to allow record extra info to alternative and display on dashboard. (@tranngocsam, #460) Bugfixes: - Avoid crashing on Ruby 2.4 for numeric strings (@flori, #470) - Fix issue where redis isn't required (@tomciopp , #466) Misc: - Avoid variable_size_secure_compare private method (@eliotsykes, #465) ## 2.2.0 (November 11th, 2016) **Backwards incompatible!** Redis keys are renamed. Please make sure all running tests are completed before you upgrade, as they will reset. Features: - Remove dependency on Redis::Namespace (@bschaeffer, #425) - Make resetting on experiment change optional (@moggyboy, #430) - Add ability to force alternative on dashboard (@ccallebs, #437) Bugfixes: - Fix variations reset across page loads for multiple=control and improve coverage (@Vasfed, #432) Misc: - Remove Explicit Return (@BradHudson, #441) - Update Redis config docs (@bschaeffer, #422) - Harden HTTP Basic snippet against timing attacks (@eliotsykes, #443) - Removed a couple old ruby 1.8 hacks (@andrew, #456) - Run tests on rails 5 (@andrew, #457) - Fixed a few codeclimate warnings (@andrew, #458) - Use codeclimate for test coverage (@andrew #455) ## 2.1.0 (August 8th, 2016) Features: - Support REDIS_PROVIDER variable used in Heroku (@kartikluke, #426) ## 2.0.0 (July 17th, 2016) Breaking changes: - Removed deprecated `finished` and `begin_experiment` methods - Namespaced override param to avoid potential clashes (@henrik, #398) ## 1.7.0 (June 28th, 2016) Features: - Running concurrent experiments on same endpoint/view (@karmakaze, #421) ## 1.6.0 (June 16th, 2016) Features: - Add Dual Redis(logged-in)/cookie(logged-out) persistence adapter (@karmakaze, #420) ## 1.5.0 (June 8th, 2016) Features: - Add `expire_seconds:` TTL option to RedisAdapter (@karmakaze, #409) - Optional custom persistence adapter (@ndelage, #411) Misc: - Use fakeredis for testing (@andrew, #412) ## 1.4.5 (June 7th, 2016) Bugfixes: - FIX Negative numbers on non-finished (@divineforest, #408) - Eliminate extra RedisAdapter hget (@karmakaze, #407) - Remove unecessary code from Experiment class (@pakallis, #391, #392, #393) Misc: - Simplify Configuration#normalized_experiments (@pakallis, #395) - Clarify test running instructions (@henrik, #397) ## 1.4.4 (May 9th, 2016) Bugfixes: - Increment participation if store override is true and no experiment key exists (@spheric, #380) Misc: - Deprecated `finished` method in favour of `ab_finished` (@andreibondarev, #389) - Added minimum version requirement to simple-random - Clarify finished with first option being a hash in Readme (@henrik, #382) - Refactoring the User abstraction (@andreibondarev, #384) ## 1.4.3 (April 28th, 2016) Features: - add on_trial callback whenever a trial is started (@mtyeh411, #375) Bugfixes: - Allow algorithm configuration at experiment level (@007sumit, #376) Misc: - only choose override if it exists as valid alternative (@spheric, #377) ## 1.4.2 (April 25th, 2016) Misc: - Deprecated some legacy methods (@andreibondarev, #374) ## 1.4.1 (April 21st, 2016) Bugfixes: - respect manual start configuration after an experiment has been deleted (@mtyeh411, #372) Misc: - Introduce goals collection to reduce complexity of Experiment#save (@pakallis, #365) - Revise specs according to http://betterspecs.org/ (@hkliya, #369) ## 1.4.0 (April 2nd, 2016) Features: - Added experiment filters to dashboard (@ccallebs, #363, #364) - Added Contributor Covenant Code of Conduct ## 1.3.2 (January 2nd, 2016) Bugfixes: - Fix deleting experiments in from the updated dashboard (@craigmcnamara, #352) ## 1.3.1 (January 1st, 2016) Bugfixes: - Fix the dashboard for experiments with ‘/‘ in the name. (@craigmcnamara, #349) ## 1.3.0 (October 20th, 2015) Features: - allow for custom redis_url different from ENV variable (@davidgrieser, #323) - add ability to change the length of the persistence cookie (@peterylai, #335) Bugfixes: - Rescue from Redis::BaseError instead of Redis::CannotConnectError (@nfm, #342) - Fix active experiments when experiment is on a later version (@ndrisso, #331) - Fix caching of winning alternative (@nfm, #329) Misc: - Remove duplication from Experiment#save (@pakallis, #333) - Remove unnecessary argument from Experiment#write_to_alternative (@t4deu, #332) ## 1.2.1 (May 17th, 2015) Features: - Handle redis DNS resolution failures gracefully (@fusion2004, #310) - Push metadata to ab_test block (@ekorneeff, #296) - Helper methods are now private when included in controllers (@ipoval, #303) Bugfixes: - Return an empty hash as metadata when Split is disabled (@tomasdundacek, #313) - Don't use capture helper from ActionView (@tomasdundacek, #312) Misc: - Remove body "max-width" from dashboard (@xicreative, #299) - fix private for class methods (@ipoval, #301) - minor memoization fix in spec (@ipoval, #304) - Minor documentation fixes (#295, #297, #305, #308) ## 1.2.0 (January 24th, 2015) Features: - Configure redis using environment variables if available (@saratovsource , #293) - Store metadata on experiment configuration (@dekz, #291) Bugfixes: - Revert the Trial#complete! public API to support noargs (@dekz, #292) ## 1.1.0 (January 9th, 2015) Changes: - Public class methods on `Split::Experiment` (e.g., `find_or_create`) have been moved to `Split::ExperimentCatalog`. Features: - Decouple trial from Split::Helper (@joshdover, #286) - Helper method for Active Experiments (@blahblahblah-, #273) Misc: - Use the new travis container based infrastructure for tests (@andrew, #280) ## 1.0.0 (October 12th, 2014) Changes: - Remove support for Ruby 1.8.7 and Rails 2.3 (@qpowell, #271) ## 0.8.0 (September 25th, 2014) Features: - Added new way to calculate the probability an alternative is the winner (@caser, #266, #251) - support multiple metrics per experiment (@stevenou, #260) Bugfixes: - Avoiding call to params in EncapsulatedHelper (@afn, #257) ## 0.7.3 (September 16th, 2014) Features: - Disable all split tests via a URL parameter (@hwartig, #263) Bugfixes: - Correctly escape experiment names on dashboard (@ecaron, #265) - Handle redis connection exception error properly (@andrew, #245) ## 0.7.2 (June 12th, 2014) Features: - Show metrics on the dashboard (@swrobel, #241) Bugfixes: - Avoid nil error with ExperimentCatalog when upgrading (@danielschwartz, #253) - [SECURITY ISSUE] Only allow known alternatives as query param overrides (@ankane, #255) ## 0.7.1 (March 20th, 2014) Features: - You can now reopen experiment from the dashboard (@mikezaby, #235) Misc: - Internal code tidy up (@IanVaughan, #238) ## 0.7.0 (December 26th, 2013) Features: - Significantly improved z-score algorithm (@caser ,#221) - Better sorting of Experiments on dashboard (@wadako111, #218) Bugfixes: - Fixed start button not being displayed in some cases (@vigosan, #219) Misc: - Experiment#initialize refactoring (@nberger, #224) - Extract ExperimentStore into a seperate class (@nberger, #225) ## 0.6.6 (October 15th, 2013) Features: - Sort experiments on Dashboard so "active" ones without a winner appear first (@swrobel, #204) - Starting tests manually (@duksis, #209) Bugfixes: - Only trigger completion callback with valid Trial (@segfaultAX, #208) - Fixed bug with `resettable` when using `normalize_experiments` (@jonashuckestein, #213) Misc: - Added more bots to filter list (@lbeder, #214, #215, #216) ## 0.6.5 (August 23, 2013) Features: - Added Redis adapter for persisting experiments across sessions (@fengb, #203) Misc: - Expand upon algorithms section in README (@swrobel, #200) ## 0.6.4 (August 8, 2013) Features: - Add hooks for experiment deletion and resetting (@craigmcnamara, #198) - Allow Split::Helper to be used outside of a controller (@nfm, #190) - Show current Rails/Rack Env in dashboard (@rceee, #187) Bugfixes: - Fix whiplash algorithm when using goals (@swrobel, #193) Misc: - Refactor dashboard js (@buddhamagnet) ## 0.6.3 (July 8, 2013) Features: - Add hooks for Trial#choose! and Trial#complete! (@bmarini, #176) Bugfixes: - Stores and parses Experiment's start_time as a UNIX integer (@joeroot, #177) ## 0.6.2 (June 6, 2013) Features: - Rails 2.3 compatibility (@bhcarpenter, #167) - Adding possibility to store overridden alternative (@duksis, #173) Misc: - Now testing against multiple versions of rails ## 0.6.1 (May 4, 2013) Bugfixes: - Use the specified algorithm for the experiment instead of the default (@woodhull, #165) Misc: - Ensure experiements are valid when configuring (@ashmckenzie, #159) - Allow arrays to be passed to ab_test (@fenelon, #156) ## 0.6.0 (April 4, 2013) Features: - Support for Ruby 2.0.0 (@phoet, #142) - Multiple Goals (@liujin, #109) - Ignoring IPs using Regular Expressions (@waynemoore, #119) - Added ability to add more bots to the default list (@themgt, #140) - Allow custom configuration of user blocking logic (@phoet , #148) Bugfixes: - Fixed regression in handling of config files (@iangreenleaf, #115) - Fixed completion rate increases for experiments users aren't participating in (@philnash, #67) - Handle exceptions from invalid JSON in cookies (@iangreenleaf, #126) Misc: - updated minimum json version requirement - Refactor Yaml Configuration (@rtwomey, #124) - Refactoring of Experiments (@iangreenleaf @tamird, #117 #118) - Added more known Bots, including Pingdom, Bing, YandexBot (@julesie, @zinkkrysty, @dimko) - Improved Readme (@iangreenleaf @phoet) ## 0.5.0 (January 28, 2013) Features: - Persistence Adapters: Cookies and Session (@patbenatar, #98) - Configure experiments from a hash (@iangreenleaf, #97) - Pluggable sampling algorithms (@woodhull, #105) Bugfixes: - Fixed negative number of non-finished rates (@philnash, #83) - Fixed behaviour of finished(:reset => false) (@philnash, #88) - Only take into consideration positive z-scores (@thomasmaas, #96) - Amended ab_test method to raise ArgumentError if passed integers or symbols as alternatives (@buddhamagnet, #81) ## 0.4.6 (October 28, 2012) Features: - General code quality improvements (@buddhamagnet, #79) Bugfixes: - Don't increment the experiment counter if user has finished (@dimko, #78) - Fixed an incorrect test (@jaywengrow, #74) ## 0.4.5 (August 30, 2012) Bugfixes: - Fixed header gradient in FF/Opera (@philnash, #69) - Fixed reseting of experiment in session (@apsoto, #43) ## 0.4.4 (August 9, 2012) Features: - Allow parameter overrides, even without Redis. (@bhcarpenter, #62) Bugfixes: - Fixes version number always increasing when alternatives are changed (@philnash, #63) - updated guard-rspec to version 1.2 ## 0.4.3 (July 8, 2012) Features: - redis failover now recovers from all redis-related exceptions ## 0.4.2 (June 1, 2012) Features: - Now works with v3.0 of redis gem Bugfixes: - Fixed redis failover on Rubinius ## 0.4.1 (April 6, 2012) Features: - Added configuration option to disable Split testing (@ilyakatz, #45) Bugfixes: - Fix weights for existing experiments (@andreas, #40) - Fixed dashboard range error (@andrew, #42) ## 0.4.0 (March 7, 2012) **IMPORTANT** If using ruby 1.8.x and weighted alternatives you should always pass the control alternative through as the second argument with any other alternatives as a third argument because the order of the hash is not preserved in ruby 1.8, ruby 1.9 users are not affected by this bug. Features: - Experiments now record when they were started (@vrish88, #35) - Old versions of experiments in sessions are now cleaned up - Avoid users participating in multiple experiments at once (#21) Bugfixes: - Overriding alternatives doesn't work for weighted alternatives (@layflags, #34) - confidence_level helper should handle tiny z-scores (#23) ## 0.3.3 (February 16, 2012) Bugfixes: - Fixed redis failover when a block was passed to ab_test (@layflags, #33) ## 0.3.2 (February 12, 2012) Features: - Handle redis errors gracefully (@layflags, #32) ## 0.3.1 (November 19, 2011) Features: - General code tidy up (@ryanlecompte, #22, @mocoso, #28) - Lazy loading data from Redis (@lautis, #25) Bugfixes: - Handle unstarted experiments (@mocoso, #27) - Relaxed Sinatra version requirement (@martinclu, #24) ## 0.3.0 (October 9, 2011) Features: - Redesigned dashboard (@mrappleton, #17) - Use atomic increments in redis for better concurrency (@lautis, #18) - Weighted alternatives Bugfixes: - Fix to allow overriding of experiments that aren't on version 1 ## 0.2.4 (July 18, 2011) Features: - Added option to finished to not reset the users session Bugfixes: - Only allow strings as alternatives, fixes strange errors when passing true/false or symbols ## 0.2.3 (June 26, 2011) Features: - Experiments can now be deleted from the dashboard - ab_test helper now accepts a block - Improved dashboard Bugfixes: - After resetting an experiment, existing users of that experiment will also be reset ## 0.2.2 (June 11, 2011) Features: - Updated redis-namespace requirement to 1.0.3 - Added a configuration object for changing options - Robot regex can now be changed via a configuration options - Added ability to ignore visits from specified IP addresses - Dashboard now shows percentage improvement of alternatives compared to the control - If the alternatives of an experiment are changed it resets the experiment and uses the new alternatives Bugfixes: - Saving an experiment multiple times no longer creates duplicate alternatives ## 0.2.1 (May 29, 2011) Bugfixes: - Convert legacy sets to lists to avoid exceptions during upgrades from 0.1.x ## 0.2.0 (May 29, 2011) Features: - Override an alternative via a url parameter - Experiments can now be reset from the dashboard - The first alternative is now considered the control - General dashboard usability improvements - Robots are ignored and given the control alternative Bugfixes: - Alternatives are now store in a list rather than a set to ensure consistent ordering - Fixed diving by zero errors ## 0.1.1 (May 18, 2011) Bugfixes: - More Robust conversion rate display on dashboard - Ensure `Split::Version` is available everywhere, fixed dashboard ## 0.1.0 (May 17, 2011) Initial Release <MSG> Add missing entry to the changelog <DFF> @@ -6,6 +6,7 @@ Bugfixes: - Only block Pinterest bot (@huoxito, #606) - Respect experiment defaults when loading experiments in initializer. (@mattwd7, #599) - Removes metadata key when it updated to nil (@andrehjr, #633) +- Force experiment does not count for metrics (@andrehjr, #637) Features: - Make goals accessible via on_trial_complete callbacks (@robin-phung, #625)
1
Add missing entry to the changelog
0
.md
md
mit
splitrb/split
10072326
<NME> README.md <BEF> # [Split](https://libraries.io/rubygems/split) [![Gem Version](https://badge.fury.io/rb/split.svg)](http://badge.fury.io/rb/split) ![Build status](https://github.com/splitrb/split/actions/workflows/ci.yml/badge.svg?branch=main) [![Code Climate](https://codeclimate.com/github/splitrb/split/badges/gpa.svg)](https://codeclimate.com/github/splitrb/split) [![Test Coverage](https://codeclimate.com/github/splitrb/split/badges/coverage.svg)](https://codeclimate.com/github/splitrb/split/coverage) [![standard-readme compliant](https://img.shields.io/badge/readme%20style-standard-brightgreen.svg?style=flat-square)](https://github.com/RichardLitt/standard-readme) [![Open Source Helpers](https://www.codetriage.com/splitrb/split/badges/users.svg)](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"])) alternatives: ["a", "b"], metadata: { "a" => {"text" => "Have a fantastic day"}, "b" => {"text" => "Don't get hit by a bus"}, } }, } end ``` 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 ![split_screenshot](https://raw.githubusercontent.com/caser/caser.github.io/master/dashboard.png) ## 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> Update README.md Remove redundant commas <DFF> @@ -445,9 +445,9 @@ Split.configure do |config| alternatives: ["a", "b"], metadata: { "a" => {"text" => "Have a fantastic day"}, - "b" => {"text" => "Don't get hit by a bus"}, + "b" => {"text" => "Don't get hit by a bus"} } - }, + } } end ```
2
Update README.md
2
.md
md
mit
splitrb/split
10072327
<NME> README.md <BEF> # [Split](https://libraries.io/rubygems/split) [![Gem Version](https://badge.fury.io/rb/split.svg)](http://badge.fury.io/rb/split) ![Build status](https://github.com/splitrb/split/actions/workflows/ci.yml/badge.svg?branch=main) [![Code Climate](https://codeclimate.com/github/splitrb/split/badges/gpa.svg)](https://codeclimate.com/github/splitrb/split) [![Test Coverage](https://codeclimate.com/github/splitrb/split/badges/coverage.svg)](https://codeclimate.com/github/splitrb/split/coverage) [![standard-readme compliant](https://img.shields.io/badge/readme%20style-standard-brightgreen.svg?style=flat-square)](https://github.com/RichardLitt/standard-readme) [![Open Source Helpers](https://www.codetriage.com/splitrb/split/badges/users.svg)](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"])) alternatives: ["a", "b"], metadata: { "a" => {"text" => "Have a fantastic day"}, "b" => {"text" => "Don't get hit by a bus"}, } }, } end ``` 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 ![split_screenshot](https://raw.githubusercontent.com/caser/caser.github.io/master/dashboard.png) ## 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> Update README.md Remove redundant commas <DFF> @@ -445,9 +445,9 @@ Split.configure do |config| alternatives: ["a", "b"], metadata: { "a" => {"text" => "Have a fantastic day"}, - "b" => {"text" => "Don't get hit by a bus"}, + "b" => {"text" => "Don't get hit by a bus"} } - }, + } } end ```
2
Update README.md
2
.md
md
mit
splitrb/split
10072328
<NME> README.md <BEF> # [Split](https://libraries.io/rubygems/split) [![Gem Version](https://badge.fury.io/rb/split.svg)](http://badge.fury.io/rb/split) ![Build status](https://github.com/splitrb/split/actions/workflows/ci.yml/badge.svg?branch=main) [![Code Climate](https://codeclimate.com/github/splitrb/split/badges/gpa.svg)](https://codeclimate.com/github/splitrb/split) [![Test Coverage](https://codeclimate.com/github/splitrb/split/badges/coverage.svg)](https://codeclimate.com/github/splitrb/split/coverage) [![standard-readme compliant](https://img.shields.io/badge/readme%20style-standard-brightgreen.svg?style=flat-square)](https://github.com/RichardLitt/standard-readme) [![Open Source Helpers](https://www.codetriage.com/splitrb/split/badges/users.svg)](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"])) alternatives: ["a", "b"], metadata: { "a" => {"text" => "Have a fantastic day"}, "b" => {"text" => "Don't get hit by a bus"}, } }, } end ``` 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 ![split_screenshot](https://raw.githubusercontent.com/caser/caser.github.io/master/dashboard.png) ## 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> Update README.md Remove redundant commas <DFF> @@ -445,9 +445,9 @@ Split.configure do |config| alternatives: ["a", "b"], metadata: { "a" => {"text" => "Have a fantastic day"}, - "b" => {"text" => "Don't get hit by a bus"}, + "b" => {"text" => "Don't get hit by a bus"} } - }, + } } end ```
2
Update README.md
2
.md
md
mit
splitrb/split
10072329
<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)`) # 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 # 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 Railtie < Rails::Railtie config.before_initialize { Split.configure {} } end else else Split.configure { } end <MSG> Keep railtie defined under the Split gem namespace <DFF> @@ -74,7 +74,7 @@ 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 Railtie < Rails::Railtie + class Split::Railtie < Rails::Railtie config.before_initialize { Split.configure {} } end else
1
Keep railtie defined under the Split gem namespace
1
.rb
rb
mit
splitrb/split
10072330
<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)`) # 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 # 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 Railtie < Rails::Railtie config.before_initialize { Split.configure {} } end else else Split.configure { } end <MSG> Keep railtie defined under the Split gem namespace <DFF> @@ -74,7 +74,7 @@ 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 Railtie < Rails::Railtie + class Split::Railtie < Rails::Railtie config.before_initialize { Split.configure {} } end else
1
Keep railtie defined under the Split gem namespace
1
.rb
rb
mit
splitrb/split
10072331
<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)`) # 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 # 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 Railtie < Rails::Railtie config.before_initialize { Split.configure {} } end else else Split.configure { } end <MSG> Keep railtie defined under the Split gem namespace <DFF> @@ -74,7 +74,7 @@ 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 Railtie < Rails::Railtie + class Split::Railtie < Rails::Railtie config.before_initialize { Split.configure {} } end else
1
Keep railtie defined under the Split gem namespace
1
.rb
rb
mit
splitrb/split
10072332
<NME> webpack.config.js <BEF> ADDFILE <MSG> chore(package.json): Reinit package.json with new dependencies <DFF> @@ -0,0 +1,29 @@ +var path = require('path'); +var webpack = require('webpack'); + +module.exports = { + context: path.resolve('src'), + devtool: "source-map", + entry: { + 'semantic-ui-angular': './index', + 'semantic-ui-angular.min': './index' + }, + output: { + path: path.resolve('dist'), + filename: '[name].js' + }, + plugins: [ + new webpack.optimize.UglifyJsPlugin({ + include: /\.min\.js$/, + minimize: true + }) + ], + module: { + loaders: [ + { test: /\.ts?$/, loader: 'ts-loader' } + ] + }, + resolve: { + extensions: ['', '.ts', '.js'] + } +};
29
chore(package.json): Reinit package.json with new dependencies
0
.js
config
mit
Semantic-Org/Semantic-UI-Angular
10072333
<NME> webpack.config.js <BEF> ADDFILE <MSG> chore(package.json): Reinit package.json with new dependencies <DFF> @@ -0,0 +1,29 @@ +var path = require('path'); +var webpack = require('webpack'); + +module.exports = { + context: path.resolve('src'), + devtool: "source-map", + entry: { + 'semantic-ui-angular': './index', + 'semantic-ui-angular.min': './index' + }, + output: { + path: path.resolve('dist'), + filename: '[name].js' + }, + plugins: [ + new webpack.optimize.UglifyJsPlugin({ + include: /\.min\.js$/, + minimize: true + }) + ], + module: { + loaders: [ + { test: /\.ts?$/, loader: 'ts-loader' } + ] + }, + resolve: { + extensions: ['', '.ts', '.js'] + } +};
29
chore(package.json): Reinit package.json with new dependencies
0
.js
config
mit
Semantic-Org/Semantic-UI-Angular
10072334
<NME> webpack.config.js <BEF> ADDFILE <MSG> chore(package.json): Reinit package.json with new dependencies <DFF> @@ -0,0 +1,29 @@ +var path = require('path'); +var webpack = require('webpack'); + +module.exports = { + context: path.resolve('src'), + devtool: "source-map", + entry: { + 'semantic-ui-angular': './index', + 'semantic-ui-angular.min': './index' + }, + output: { + path: path.resolve('dist'), + filename: '[name].js' + }, + plugins: [ + new webpack.optimize.UglifyJsPlugin({ + include: /\.min\.js$/, + minimize: true + }) + ], + module: { + loaders: [ + { test: /\.ts?$/, loader: 'ts-loader' } + ] + }, + resolve: { + extensions: ['', '.ts', '.js'] + } +};
29
chore(package.json): Reinit package.json with new dependencies
0
.js
config
mit
Semantic-Org/Semantic-UI-Angular
10072335
<NME> convert.ts <BEF> import { equal } from 'assert'; import parser, { ParserOptions } from '../src'; import stringify from './assets/stringify-node'; function parse(abbr: string, options?: ParserOptions) { return stringify(parser(abbr, options)); } describe('Convert token abbreviations', () => { it('basic', () => { equal(parse('input[value="text$"]*2'), '<input*2@0 value="text1"></input><input*2@1 value="text2"></input>'); equal(parse('ul>li.item$*3'), '<ul><li*3@0 class="item1"></li><li*3@1 class="item2"></li><li*3@2 class="item3"></li></ul>'); equal(parse('ul>li.item$*', { text: ['foo$', 'bar$'] }), '<ul><li*2@0 class="item1">foo$</li><li*2@1 class="item2">bar$</li></ul>'); equal(parse('ul>li[class=$#]{item $}*', { text: ['foo$', 'bar$'] }), '<ul><li*2@0 class="foo$">item 1</li><li*2@1 class="bar$">item 2</li></ul>'); equal(parse('ul>li.item$*'), '<ul><li*1@0 class="item1"></li></ul>'); equal(parse('ul>li.item$*', { text: ['foo.bar', 'hello.world'] }), '<ul><li*2@0 class="item1">foo.bar</li><li*2@1 class="item2">hello.world</li></ul>'); equal(parse('p{hi}', { text: ['hello'] }), '<p>hihello</p>'); equal(parse('p*{hi}', { text: ['1', '2'] }), '<p*2@0>hi1</p><p*2@1>hi2</p>'); equal(parse('div>p+p{hi}', { text: ['hello'] }), '<div><p></p><p>hihello</p></div>'); equal(parse('html[lang=${lang}]'), '<html lang="lang"></html>'); equal(parse('html.one.two'), '<html class="one", class="two"></html>'); equal(parse('html.one[two=three]'), '<html class="one", two="three"></html>'); equal(parse('div{[}+a{}'), '<div>[</div><a></a>'); }); it('unroll', () => { equal(parse('a>(b>c)+d'), '<a><b><c></c></b><d></d></a>'); equal(parse('(a>b)+(c>d)'), '<a><b></b></a><c><d></d></c>'); equal(parse('a>((b>c)(d>e))f'), '<a><b><c></c></b><d><e></e></d><f></f></a>'); equal(parse('p>{foo}>div'), '<p><?>foo</?><div></div></p>'); equal(parse('p>{foo ${0}}>div'), '<p><?>foo ${0}<div></div></?></p>'); }); }); }); it('limit unroll', () => { // Limit amount of repeated elements equal(parse('a*10', { maxRepeat: 5 }), '<a*10@0></a><a*10@1></a><a*10@2></a><a*10@3></a><a*10@4></a>'); equal(parse('a*10'), '<a*10@0></a><a*10@1></a><a*10@2></a><a*10@3></a><a*10@4></a><a*10@5></a><a*10@6></a><a*10@7></a><a*10@8></a><a*10@9></a>'); equal(parse('a*3>b*3', { maxRepeat: 5 }), '<a*3@0><b*3@0></b><b*3@1></b><b*3@2></b></a><a*3@1><b*3@0></b></a>'); }); it('parent repeater', () => { equal(parse('a$*2>b$*3/'), '<a1*2@0><b1*3@0 /><b2*3@1 /><b3*3@2 /></a1><a2*2@1><b1*3@0 /><b2*3@1 /><b3*3@2 /></a2>'); equal(parse('a$*2>b$@^*3/'), '<a1*2@0><b1*3@0 /><b2*3@1 /><b3*3@2 /></a1><a2*2@1><b4*3@0 /><b5*3@1 /><b6*3@2 /></a2>'); }); it('href', () => { equal(parse('a', { href: true, text: 'https://www.google.it' }), '<a href="https://www.google.it">https://www.google.it</a>'); equal(parse('a', { href: true, text: 'www.google.it' }), '<a href="http://www.google.it">www.google.it</a>'); equal(parse('a', { href: true, text: 'google.it' }), '<a href="">google.it</a>'); equal(parse('a', { href: true, text: 'test here' }), '<a href="">test here</a>'); equal(parse('a', { href: true, text: 'test@domain.com' }), '<a href="mailto:test@domain.com">test@domain.com</a>'); equal(parse('a', { href: true, text: 'test here test@domain.com' }), '<a href="">test here test@domain.com</a>'); equal(parse('a', { href: true, text: 'test here www.domain.com' }), '<a href="">test here www.domain.com</a>'); equal(parse('a[href=]', { href: true, text: 'https://www.google.it' }), '<a href="https://www.google.it">https://www.google.it</a>'); equal(parse('a[href=]', { href: true, text: 'www.google.it' }), '<a href="http://www.google.it">www.google.it</a>'); equal(parse('a[href=]', { href: true, text: 'google.it' }), '<a href="">google.it</a>'); equal(parse('a[href=]', { href: true, text: 'test here' }), '<a href="">test here</a>'); equal(parse('a[href=]', { href: true, text: 'test@domain.com' }), '<a href="mailto:test@domain.com">test@domain.com</a>'); equal(parse('a[href=]', { href: true, text: 'test here test@domain.com' }), '<a href="">test here test@domain.com</a>'); equal(parse('a[href=]', { href: true, text: 'test here www.domain.com' }), '<a href="">test here www.domain.com</a>'); equal(parse('a[class=here]', { href: true, text: 'test@domain.com' }), '<a class="here", href="mailto:test@domain.com">test@domain.com</a>'); equal(parse('a.here', { href: true, text: 'www.domain.com' }), '<a class="here", href="http://www.domain.com">www.domain.com</a>'); equal(parse('a[class=here]', { href: true, text: 'test here test@domain.com' }), '<a class="here", href="">test here test@domain.com</a>'); equal(parse('a.here', { href: true, text: 'test here www.domain.com' }), '<a class="here", href="">test here www.domain.com</a>'); equal(parse('a[href="www.google.it"]', { href: false, text: 'test' }), '<a href="www.google.it">test</a>'); equal(parse('a[href="www.example.com"]', { href: true, text: 'www.google.it' }), '<a href="www.example.com">www.google.it</a>'); }); it('wrap basic', () => { equal(parse('p', { text: 'test' }), '<p>test</p>'); equal(parse('p', { text: ['test'] }), '<p>test</p>'); equal(parse('p', { text: ['test1', 'test2'] }), '<p>test1\ntest2</p>'); equal(parse('p', { text: ['test1', '', 'test2'] }), '<p>test1\n\ntest2</p>'); equal(parse('p*', { text: ['test1', 'test2'] }), '<p*2@0>test1</p><p*2@1>test2</p>'); equal(parse('p*', { text: ['test1', '', 'test2'] }), '<p*2@0>test1</p><p*2@1>test2</p>'); }) }); <MSG> Option to limit amount of unrolled elements <DFF> @@ -33,4 +33,11 @@ describe('Convert token abbreviations', () => { equal(parse('p>{foo}>div'), '<p><?>foo</?><div></div></p>'); equal(parse('p>{foo ${0}}>div'), '<p><?>foo ${0}<div></div></?></p>'); }); + + it('limit unroll', () => { + // Limit amount of repeated elements + equal(parse('a*10', { maxRepeat: 5 }), '<a*10@0></a><a*10@1></a><a*10@2></a><a*10@3></a><a*10@4></a>'); + equal(parse('a*10'), '<a*10@0></a><a*10@1></a><a*10@2></a><a*10@3></a><a*10@4></a><a*10@5></a><a*10@6></a><a*10@7></a><a*10@8></a><a*10@9></a>'); + equal(parse('a*3>b*3', { maxRepeat: 5 }), '<a*3@0><b*3@0></b><b*3@1></b><b*3@2></b></a><a*3@1><b*3@0></b></a>'); + }); });
7
Option to limit amount of unrolled elements
0
.ts
ts
mit
emmetio/emmet
10072336
<NME> convert.ts <BEF> import { equal } from 'assert'; import parser, { ParserOptions } from '../src'; import stringify from './assets/stringify-node'; function parse(abbr: string, options?: ParserOptions) { return stringify(parser(abbr, options)); } describe('Convert token abbreviations', () => { it('basic', () => { equal(parse('input[value="text$"]*2'), '<input*2@0 value="text1"></input><input*2@1 value="text2"></input>'); equal(parse('ul>li.item$*3'), '<ul><li*3@0 class="item1"></li><li*3@1 class="item2"></li><li*3@2 class="item3"></li></ul>'); equal(parse('ul>li.item$*', { text: ['foo$', 'bar$'] }), '<ul><li*2@0 class="item1">foo$</li><li*2@1 class="item2">bar$</li></ul>'); equal(parse('ul>li[class=$#]{item $}*', { text: ['foo$', 'bar$'] }), '<ul><li*2@0 class="foo$">item 1</li><li*2@1 class="bar$">item 2</li></ul>'); equal(parse('ul>li.item$*'), '<ul><li*1@0 class="item1"></li></ul>'); equal(parse('ul>li.item$*', { text: ['foo.bar', 'hello.world'] }), '<ul><li*2@0 class="item1">foo.bar</li><li*2@1 class="item2">hello.world</li></ul>'); equal(parse('p{hi}', { text: ['hello'] }), '<p>hihello</p>'); equal(parse('p*{hi}', { text: ['1', '2'] }), '<p*2@0>hi1</p><p*2@1>hi2</p>'); equal(parse('div>p+p{hi}', { text: ['hello'] }), '<div><p></p><p>hihello</p></div>'); equal(parse('html[lang=${lang}]'), '<html lang="lang"></html>'); equal(parse('html.one.two'), '<html class="one", class="two"></html>'); equal(parse('html.one[two=three]'), '<html class="one", two="three"></html>'); equal(parse('div{[}+a{}'), '<div>[</div><a></a>'); }); it('unroll', () => { equal(parse('a>(b>c)+d'), '<a><b><c></c></b><d></d></a>'); equal(parse('(a>b)+(c>d)'), '<a><b></b></a><c><d></d></c>'); equal(parse('a>((b>c)(d>e))f'), '<a><b><c></c></b><d><e></e></d><f></f></a>'); equal(parse('p>{foo}>div'), '<p><?>foo</?><div></div></p>'); equal(parse('p>{foo ${0}}>div'), '<p><?>foo ${0}<div></div></?></p>'); }); }); }); it('limit unroll', () => { // Limit amount of repeated elements equal(parse('a*10', { maxRepeat: 5 }), '<a*10@0></a><a*10@1></a><a*10@2></a><a*10@3></a><a*10@4></a>'); equal(parse('a*10'), '<a*10@0></a><a*10@1></a><a*10@2></a><a*10@3></a><a*10@4></a><a*10@5></a><a*10@6></a><a*10@7></a><a*10@8></a><a*10@9></a>'); equal(parse('a*3>b*3', { maxRepeat: 5 }), '<a*3@0><b*3@0></b><b*3@1></b><b*3@2></b></a><a*3@1><b*3@0></b></a>'); }); it('parent repeater', () => { equal(parse('a$*2>b$*3/'), '<a1*2@0><b1*3@0 /><b2*3@1 /><b3*3@2 /></a1><a2*2@1><b1*3@0 /><b2*3@1 /><b3*3@2 /></a2>'); equal(parse('a$*2>b$@^*3/'), '<a1*2@0><b1*3@0 /><b2*3@1 /><b3*3@2 /></a1><a2*2@1><b4*3@0 /><b5*3@1 /><b6*3@2 /></a2>'); }); it('href', () => { equal(parse('a', { href: true, text: 'https://www.google.it' }), '<a href="https://www.google.it">https://www.google.it</a>'); equal(parse('a', { href: true, text: 'www.google.it' }), '<a href="http://www.google.it">www.google.it</a>'); equal(parse('a', { href: true, text: 'google.it' }), '<a href="">google.it</a>'); equal(parse('a', { href: true, text: 'test here' }), '<a href="">test here</a>'); equal(parse('a', { href: true, text: 'test@domain.com' }), '<a href="mailto:test@domain.com">test@domain.com</a>'); equal(parse('a', { href: true, text: 'test here test@domain.com' }), '<a href="">test here test@domain.com</a>'); equal(parse('a', { href: true, text: 'test here www.domain.com' }), '<a href="">test here www.domain.com</a>'); equal(parse('a[href=]', { href: true, text: 'https://www.google.it' }), '<a href="https://www.google.it">https://www.google.it</a>'); equal(parse('a[href=]', { href: true, text: 'www.google.it' }), '<a href="http://www.google.it">www.google.it</a>'); equal(parse('a[href=]', { href: true, text: 'google.it' }), '<a href="">google.it</a>'); equal(parse('a[href=]', { href: true, text: 'test here' }), '<a href="">test here</a>'); equal(parse('a[href=]', { href: true, text: 'test@domain.com' }), '<a href="mailto:test@domain.com">test@domain.com</a>'); equal(parse('a[href=]', { href: true, text: 'test here test@domain.com' }), '<a href="">test here test@domain.com</a>'); equal(parse('a[href=]', { href: true, text: 'test here www.domain.com' }), '<a href="">test here www.domain.com</a>'); equal(parse('a[class=here]', { href: true, text: 'test@domain.com' }), '<a class="here", href="mailto:test@domain.com">test@domain.com</a>'); equal(parse('a.here', { href: true, text: 'www.domain.com' }), '<a class="here", href="http://www.domain.com">www.domain.com</a>'); equal(parse('a[class=here]', { href: true, text: 'test here test@domain.com' }), '<a class="here", href="">test here test@domain.com</a>'); equal(parse('a.here', { href: true, text: 'test here www.domain.com' }), '<a class="here", href="">test here www.domain.com</a>'); equal(parse('a[href="www.google.it"]', { href: false, text: 'test' }), '<a href="www.google.it">test</a>'); equal(parse('a[href="www.example.com"]', { href: true, text: 'www.google.it' }), '<a href="www.example.com">www.google.it</a>'); }); it('wrap basic', () => { equal(parse('p', { text: 'test' }), '<p>test</p>'); equal(parse('p', { text: ['test'] }), '<p>test</p>'); equal(parse('p', { text: ['test1', 'test2'] }), '<p>test1\ntest2</p>'); equal(parse('p', { text: ['test1', '', 'test2'] }), '<p>test1\n\ntest2</p>'); equal(parse('p*', { text: ['test1', 'test2'] }), '<p*2@0>test1</p><p*2@1>test2</p>'); equal(parse('p*', { text: ['test1', '', 'test2'] }), '<p*2@0>test1</p><p*2@1>test2</p>'); }) }); <MSG> Option to limit amount of unrolled elements <DFF> @@ -33,4 +33,11 @@ describe('Convert token abbreviations', () => { equal(parse('p>{foo}>div'), '<p><?>foo</?><div></div></p>'); equal(parse('p>{foo ${0}}>div'), '<p><?>foo ${0}<div></div></?></p>'); }); + + it('limit unroll', () => { + // Limit amount of repeated elements + equal(parse('a*10', { maxRepeat: 5 }), '<a*10@0></a><a*10@1></a><a*10@2></a><a*10@3></a><a*10@4></a>'); + equal(parse('a*10'), '<a*10@0></a><a*10@1></a><a*10@2></a><a*10@3></a><a*10@4></a><a*10@5></a><a*10@6></a><a*10@7></a><a*10@8></a><a*10@9></a>'); + equal(parse('a*3>b*3', { maxRepeat: 5 }), '<a*3@0><b*3@0></b><b*3@1></b><b*3@2></b></a><a*3@1><b*3@0></b></a>'); + }); });
7
Option to limit amount of unrolled elements
0
.ts
ts
mit
emmetio/emmet
10072337
<NME> jquery.meow.css <BEF> .meows { position: fixed; top: 0; right: 0; } .meow { margin: 20px 20px 0 0; position: relative; } .meow .inner { background: #191919; zoom: 1; filter: alpha(opacity = 75); background: rgba(25, 25, 25, .75); border: 2px solid transparent; -moz-border-radius: 10px; -webket-border-radius: 10px; -khtml-border-radius: 10px; -o-border-radius: 10px; border-radius: 10px; -moz-box-shadow: 2px 2px 10px rgba(25, 25, 25, .25); -webkit-box-shadow: 2px 2px 10px rgba(25, 25, 25, .25); -khtml-box-shadow: 2px 2px 10px rgba(25, 25, 25, .25); -o-box-shadow: 2px 2px 10px rgba(25, 25, 25, .25); box-shadow: 2px 2px 10px rgba(25, 25, 25, .25); color: #fff; font-family: Helvetica, Arial, sans-serif; font-size: 15px; padding: 10px; text-shadow: 1px 1px 3px #000; width: 300px; min-height: 48px; } .meow .inner:after { content: "\0200"; display: block; clear: both; visibility: hidden; line-height: 0; height: 0; } .meow.hover .inner { border: 2px solid #fff; } .meow .inner h1 { font-size: 14px; font-weight: bold; margin: 0; padding: 0; line-height: 1; } .meow .inner .icon { width: 48px; height: 48px; float: left; margin-right: 6px; } .meow .inner .icon img { max-width: 48px; max-height: 48px; } .meow .inner .close { display: none; } .meow.hover .inner .close { background: #191919; zoom: 1; filter: alpha(opacity = 75); background: rgba(25, 25, 25, .75); border: 2px solid #ffffff; -khtml-border-radius: 18px; -moz-border-radius: 18px; -o-border-radius: 18px; -webket-border-radius: 18px; border-radius: 18px; color: #ffffff; display: block; font-size: 22px; font-weight: 500; height: 18px; left: 4px; line-height: 14px; position: absolute; text-align: center; text-decoration: none; top: 4px; width: 18px; } .meows { position: fixed; top: 0; right: 0; } .meow { position: relative; margin: 20px 20px 0 0; } .meow .inner { width: 300px; min-height: 48px; padding: 10px; font-family: Helvetica, Arial, sans-serif; font-size: 15px; color: #fff; text-shadow: 1px 1px 3px #000; background: #191919; border: 2px solid transparent; -webkit-border-radius: 10px; -khtml-border-radius: 10px; -moz-border-radius: 10px; -ms-border-radius: 10px; -o-border-radius: 10px; border-radius: 10px; -webkit-opacity: 0.75; -khtml-opacity: 0.75; -moz-opacity: 0.75; -ms-opacity: 0.75; -o-opacity: 0.75; opacity: 0.75; zoom: 1; -webkit-box-shadow: 2px 2px 10px rgba(25, 25, 25, 0.25); -khtml-box-shadow: 2px 2px 10px rgba(25, 25, 25, 0.25); -moz-box-shadow: 2px 2px 10px rgba(25, 25, 25, 0.25); -ms-box-shadow: 2px 2px 10px rgba(25, 25, 25, 0.25); -o-box-shadow: 2px 2px 10px rgba(25, 25, 25, 0.25); box-shadow: 2px 2px 10px rgba(25, 25, 25, 0.25); } .meow .inner:after { display: block; height: 0; clear: both; line-height: 0; content: "\0200"; visibility: hidden; } .meow.hover .inner { border: 2px solid #fff; } .meow .inner h1 { padding: 0; margin: 0; font-size: 14px; font-weight: bold; line-height: 1; } .meow .inner .icon { float: left; width: 48px; height: 48px; margin-right: 6px; } .meow .inner .icon img { max-width: 48px; max-height: 48px; } .meow .inner .close { display: none; } .meow.hover .inner .close { position: absolute; top: 4px; left: 4px; display: block; width: 18px; height: 18px; font-size: 22px; font-weight: 500; line-height: 14px; color: #ffffff; text-align: center; text-decoration: none; background: #191919; border: 2px solid #ffffff; -webkit-border-radius: 18px; -khtml-border-radius: 18px; -moz-border-radius: 18px; -ms-border-radius: 18px; -o-border-radius: 18px; border-radius: 18px; -webkit-opacity: 0.75; -khtml-opacity: 0.75; -moz-opacity: 0.75; -ms-opacity: 0.75; -o-opacity: 0.75; opacity: 0.75; zoom: 1; } <MSG> add mixins <DFF> @@ -1,88 +0,0 @@ -.meows { - position: fixed; - top: 0; - right: 0; -} -.meow { - margin: 20px 20px 0 0; - position: relative; -} -.meow .inner { - background: #191919; - zoom: 1; - filter: alpha(opacity = 75); - background: rgba(25, 25, 25, .75); - border: 2px solid transparent; - -moz-border-radius: 10px; - -webket-border-radius: 10px; - -khtml-border-radius: 10px; - -o-border-radius: 10px; - border-radius: 10px; - -moz-box-shadow: 2px 2px 10px rgba(25, 25, 25, .25); - -webkit-box-shadow: 2px 2px 10px rgba(25, 25, 25, .25); - -khtml-box-shadow: 2px 2px 10px rgba(25, 25, 25, .25); - -o-box-shadow: 2px 2px 10px rgba(25, 25, 25, .25); - box-shadow: 2px 2px 10px rgba(25, 25, 25, .25); - color: #fff; - font-family: Helvetica, Arial, sans-serif; - font-size: 15px; - padding: 10px; - text-shadow: 1px 1px 3px #000; - width: 300px; - min-height: 48px; -} -.meow .inner:after { - content: "\0200"; - display: block; - clear: both; - visibility: hidden; - line-height: 0; - height: 0; -} -.meow.hover .inner { - border: 2px solid #fff; -} -.meow .inner h1 { - font-size: 14px; - font-weight: bold; - margin: 0; - padding: 0; - line-height: 1; -} -.meow .inner .icon { - width: 48px; - height: 48px; - float: left; - margin-right: 6px; -} -.meow .inner .icon img { - max-width: 48px; - max-height: 48px; -} -.meow .inner .close { - display: none; -} -.meow.hover .inner .close { - background: #191919; - zoom: 1; - filter: alpha(opacity = 75); - background: rgba(25, 25, 25, .75); - border: 2px solid #ffffff; - -khtml-border-radius: 18px; - -moz-border-radius: 18px; - -o-border-radius: 18px; - -webket-border-radius: 18px; - border-radius: 18px; - color: #ffffff; - display: block; - font-size: 22px; - font-weight: 500; - height: 18px; - left: 4px; - line-height: 14px; - position: absolute; - text-align: center; - text-decoration: none; - top: 4px; - width: 18px; -}
0
add mixins
88
.css
meow
mit
zacstewart/Meow
10072338
<NME> jquery.meow.css <BEF> .meows { position: fixed; top: 0; right: 0; } .meow { margin: 20px 20px 0 0; position: relative; } .meow .inner { background: #191919; zoom: 1; filter: alpha(opacity = 75); background: rgba(25, 25, 25, .75); border: 2px solid transparent; -moz-border-radius: 10px; -webket-border-radius: 10px; -khtml-border-radius: 10px; -o-border-radius: 10px; border-radius: 10px; -moz-box-shadow: 2px 2px 10px rgba(25, 25, 25, .25); -webkit-box-shadow: 2px 2px 10px rgba(25, 25, 25, .25); -khtml-box-shadow: 2px 2px 10px rgba(25, 25, 25, .25); -o-box-shadow: 2px 2px 10px rgba(25, 25, 25, .25); box-shadow: 2px 2px 10px rgba(25, 25, 25, .25); color: #fff; font-family: Helvetica, Arial, sans-serif; font-size: 15px; padding: 10px; text-shadow: 1px 1px 3px #000; width: 300px; min-height: 48px; } .meow .inner:after { content: "\0200"; display: block; clear: both; visibility: hidden; line-height: 0; height: 0; } .meow.hover .inner { border: 2px solid #fff; } .meow .inner h1 { font-size: 14px; font-weight: bold; margin: 0; padding: 0; line-height: 1; } .meow .inner .icon { width: 48px; height: 48px; float: left; margin-right: 6px; } .meow .inner .icon img { max-width: 48px; max-height: 48px; } .meow .inner .close { display: none; } .meow.hover .inner .close { background: #191919; zoom: 1; filter: alpha(opacity = 75); background: rgba(25, 25, 25, .75); border: 2px solid #ffffff; -khtml-border-radius: 18px; -moz-border-radius: 18px; -o-border-radius: 18px; -webket-border-radius: 18px; border-radius: 18px; color: #ffffff; display: block; font-size: 22px; font-weight: 500; height: 18px; left: 4px; line-height: 14px; position: absolute; text-align: center; text-decoration: none; top: 4px; width: 18px; } .meows { position: fixed; top: 0; right: 0; } .meow { position: relative; margin: 20px 20px 0 0; } .meow .inner { width: 300px; min-height: 48px; padding: 10px; font-family: Helvetica, Arial, sans-serif; font-size: 15px; color: #fff; text-shadow: 1px 1px 3px #000; background: #191919; border: 2px solid transparent; -webkit-border-radius: 10px; -khtml-border-radius: 10px; -moz-border-radius: 10px; -ms-border-radius: 10px; -o-border-radius: 10px; border-radius: 10px; -webkit-opacity: 0.75; -khtml-opacity: 0.75; -moz-opacity: 0.75; -ms-opacity: 0.75; -o-opacity: 0.75; opacity: 0.75; zoom: 1; -webkit-box-shadow: 2px 2px 10px rgba(25, 25, 25, 0.25); -khtml-box-shadow: 2px 2px 10px rgba(25, 25, 25, 0.25); -moz-box-shadow: 2px 2px 10px rgba(25, 25, 25, 0.25); -ms-box-shadow: 2px 2px 10px rgba(25, 25, 25, 0.25); -o-box-shadow: 2px 2px 10px rgba(25, 25, 25, 0.25); box-shadow: 2px 2px 10px rgba(25, 25, 25, 0.25); } .meow .inner:after { display: block; height: 0; clear: both; line-height: 0; content: "\0200"; visibility: hidden; } .meow.hover .inner { border: 2px solid #fff; } .meow .inner h1 { padding: 0; margin: 0; font-size: 14px; font-weight: bold; line-height: 1; } .meow .inner .icon { float: left; width: 48px; height: 48px; margin-right: 6px; } .meow .inner .icon img { max-width: 48px; max-height: 48px; } .meow .inner .close { display: none; } .meow.hover .inner .close { position: absolute; top: 4px; left: 4px; display: block; width: 18px; height: 18px; font-size: 22px; font-weight: 500; line-height: 14px; color: #ffffff; text-align: center; text-decoration: none; background: #191919; border: 2px solid #ffffff; -webkit-border-radius: 18px; -khtml-border-radius: 18px; -moz-border-radius: 18px; -ms-border-radius: 18px; -o-border-radius: 18px; border-radius: 18px; -webkit-opacity: 0.75; -khtml-opacity: 0.75; -moz-opacity: 0.75; -ms-opacity: 0.75; -o-opacity: 0.75; opacity: 0.75; zoom: 1; } <MSG> add mixins <DFF> @@ -1,88 +0,0 @@ -.meows { - position: fixed; - top: 0; - right: 0; -} -.meow { - margin: 20px 20px 0 0; - position: relative; -} -.meow .inner { - background: #191919; - zoom: 1; - filter: alpha(opacity = 75); - background: rgba(25, 25, 25, .75); - border: 2px solid transparent; - -moz-border-radius: 10px; - -webket-border-radius: 10px; - -khtml-border-radius: 10px; - -o-border-radius: 10px; - border-radius: 10px; - -moz-box-shadow: 2px 2px 10px rgba(25, 25, 25, .25); - -webkit-box-shadow: 2px 2px 10px rgba(25, 25, 25, .25); - -khtml-box-shadow: 2px 2px 10px rgba(25, 25, 25, .25); - -o-box-shadow: 2px 2px 10px rgba(25, 25, 25, .25); - box-shadow: 2px 2px 10px rgba(25, 25, 25, .25); - color: #fff; - font-family: Helvetica, Arial, sans-serif; - font-size: 15px; - padding: 10px; - text-shadow: 1px 1px 3px #000; - width: 300px; - min-height: 48px; -} -.meow .inner:after { - content: "\0200"; - display: block; - clear: both; - visibility: hidden; - line-height: 0; - height: 0; -} -.meow.hover .inner { - border: 2px solid #fff; -} -.meow .inner h1 { - font-size: 14px; - font-weight: bold; - margin: 0; - padding: 0; - line-height: 1; -} -.meow .inner .icon { - width: 48px; - height: 48px; - float: left; - margin-right: 6px; -} -.meow .inner .icon img { - max-width: 48px; - max-height: 48px; -} -.meow .inner .close { - display: none; -} -.meow.hover .inner .close { - background: #191919; - zoom: 1; - filter: alpha(opacity = 75); - background: rgba(25, 25, 25, .75); - border: 2px solid #ffffff; - -khtml-border-radius: 18px; - -moz-border-radius: 18px; - -o-border-radius: 18px; - -webket-border-radius: 18px; - border-radius: 18px; - color: #ffffff; - display: block; - font-size: 22px; - font-weight: 500; - height: 18px; - left: 4px; - line-height: 14px; - position: absolute; - text-align: center; - text-decoration: none; - top: 4px; - width: 18px; -}
0
add mixins
88
.css
meow
mit
zacstewart/Meow
10072339
<NME> trial.rb <BEF> # frozen_string_literal: true module Split class Trial attr_accessor :goals attr_accessor :experiment attr_writer :metadata def initialize(attrs = {}) self.experiment = attrs.delete(:experiment) self.alternative = attrs.delete(:alternative) self.metadata = attrs.delete(:metadata) self.goals = attrs.delete(:goals) || [] @user = attrs.delete(:user) @options = attrs @alternative_chosen = false end def metadata @metadata ||= experiment.metadata[alternative.name] if experiment.metadata end def alternative @alternative ||= if @experiment.has_winner? @experiment.winner end end def alternative=(alternative) @alternative = if alternative.kind_of?(Split::Alternative) alternative else @experiment.alternatives.find{|a| a.name == alternative } end end def complete!(context = nil) if alternative if Array(goals).empty? alternative.increment_completion else Array(goals).each { |g| alternative.increment_completion(g) } end run_callback context, Split.configuration.on_trial_complete end end # Choose an alternative, add a participant, and save the alternative choice on the user. This # method is guaranteed to only run once, and will skip the alternative choosing process if run # a second time. def choose!(context = nil) @user.cleanup_old_experiments! # Only run the process once return alternative if @alternative_chosen new_participant = @user[@experiment.key].nil? if override_is_alternative? self.alternative = @options[:override] if should_store_alternative? && !@user[@experiment.key] self.alternative.increment_participation end elsif @options[:disabled] || Split.configuration.disabled? self.alternative = @experiment.control elsif @experiment.has_winner? self.alternative = @experiment.winner else cleanup_old_versions if exclude_user? self.alternative = @experiment.control else self.alternative = @user[@experiment.key] if alternative.nil? if @experiment.cohorting_disabled? self.alternative = @experiment.control else self.alternative = @experiment.next_alternative # Increment the number of participants since we are actually choosing a new alternative self.alternative.increment_participation run_callback context, Split.configuration.on_trial_choose end end end end new_participant_and_cohorting_disabled = new_participant && @experiment.cohorting_disabled? @user[@experiment.key] = alternative.name unless @experiment.has_winner? || !should_store_alternative? || new_participant_and_cohorting_disabled @alternative_chosen = true run_callback context, Split.configuration.on_trial unless @options[:disabled] || Split.configuration.disabled? || new_participant_and_cohorting_disabled alternative end private def run_callback(context, callback_name) context.send(callback_name, self) if callback_name && context.respond_to?(callback_name, true) end def override_is_alternative? @experiment.alternatives.map(&:name).include?(@options[:override]) end def should_store_alternative? if @options[:override] || @options[:disabled] Split.configuration.store_override else !exclude_user? end end def cleanup_old_versions if @experiment.version > 0 @user.cleanup_old_versions!(@experiment) end end def exclude_user? @options[:exclude] || @experiment.start_time.nil? || @user.max_experiments_reached?(@experiment.key) end end end <MSG> Fix Layout/SpaceBeforeBlockBraces <DFF> @@ -32,7 +32,7 @@ module Split @alternative = if alternative.kind_of?(Split::Alternative) alternative else - @experiment.alternatives.find{|a| a.name == alternative } + @experiment.alternatives.find {|a| a.name == alternative } end end
1
Fix Layout/SpaceBeforeBlockBraces
1
.rb
rb
mit
splitrb/split
10072340
<NME> trial.rb <BEF> # frozen_string_literal: true module Split class Trial attr_accessor :goals attr_accessor :experiment attr_writer :metadata def initialize(attrs = {}) self.experiment = attrs.delete(:experiment) self.alternative = attrs.delete(:alternative) self.metadata = attrs.delete(:metadata) self.goals = attrs.delete(:goals) || [] @user = attrs.delete(:user) @options = attrs @alternative_chosen = false end def metadata @metadata ||= experiment.metadata[alternative.name] if experiment.metadata end def alternative @alternative ||= if @experiment.has_winner? @experiment.winner end end def alternative=(alternative) @alternative = if alternative.kind_of?(Split::Alternative) alternative else @experiment.alternatives.find{|a| a.name == alternative } end end def complete!(context = nil) if alternative if Array(goals).empty? alternative.increment_completion else Array(goals).each { |g| alternative.increment_completion(g) } end run_callback context, Split.configuration.on_trial_complete end end # Choose an alternative, add a participant, and save the alternative choice on the user. This # method is guaranteed to only run once, and will skip the alternative choosing process if run # a second time. def choose!(context = nil) @user.cleanup_old_experiments! # Only run the process once return alternative if @alternative_chosen new_participant = @user[@experiment.key].nil? if override_is_alternative? self.alternative = @options[:override] if should_store_alternative? && !@user[@experiment.key] self.alternative.increment_participation end elsif @options[:disabled] || Split.configuration.disabled? self.alternative = @experiment.control elsif @experiment.has_winner? self.alternative = @experiment.winner else cleanup_old_versions if exclude_user? self.alternative = @experiment.control else self.alternative = @user[@experiment.key] if alternative.nil? if @experiment.cohorting_disabled? self.alternative = @experiment.control else self.alternative = @experiment.next_alternative # Increment the number of participants since we are actually choosing a new alternative self.alternative.increment_participation run_callback context, Split.configuration.on_trial_choose end end end end new_participant_and_cohorting_disabled = new_participant && @experiment.cohorting_disabled? @user[@experiment.key] = alternative.name unless @experiment.has_winner? || !should_store_alternative? || new_participant_and_cohorting_disabled @alternative_chosen = true run_callback context, Split.configuration.on_trial unless @options[:disabled] || Split.configuration.disabled? || new_participant_and_cohorting_disabled alternative end private def run_callback(context, callback_name) context.send(callback_name, self) if callback_name && context.respond_to?(callback_name, true) end def override_is_alternative? @experiment.alternatives.map(&:name).include?(@options[:override]) end def should_store_alternative? if @options[:override] || @options[:disabled] Split.configuration.store_override else !exclude_user? end end def cleanup_old_versions if @experiment.version > 0 @user.cleanup_old_versions!(@experiment) end end def exclude_user? @options[:exclude] || @experiment.start_time.nil? || @user.max_experiments_reached?(@experiment.key) end end end <MSG> Fix Layout/SpaceBeforeBlockBraces <DFF> @@ -32,7 +32,7 @@ module Split @alternative = if alternative.kind_of?(Split::Alternative) alternative else - @experiment.alternatives.find{|a| a.name == alternative } + @experiment.alternatives.find {|a| a.name == alternative } end end
1
Fix Layout/SpaceBeforeBlockBraces
1
.rb
rb
mit
splitrb/split
10072341
<NME> trial.rb <BEF> # frozen_string_literal: true module Split class Trial attr_accessor :goals attr_accessor :experiment attr_writer :metadata def initialize(attrs = {}) self.experiment = attrs.delete(:experiment) self.alternative = attrs.delete(:alternative) self.metadata = attrs.delete(:metadata) self.goals = attrs.delete(:goals) || [] @user = attrs.delete(:user) @options = attrs @alternative_chosen = false end def metadata @metadata ||= experiment.metadata[alternative.name] if experiment.metadata end def alternative @alternative ||= if @experiment.has_winner? @experiment.winner end end def alternative=(alternative) @alternative = if alternative.kind_of?(Split::Alternative) alternative else @experiment.alternatives.find{|a| a.name == alternative } end end def complete!(context = nil) if alternative if Array(goals).empty? alternative.increment_completion else Array(goals).each { |g| alternative.increment_completion(g) } end run_callback context, Split.configuration.on_trial_complete end end # Choose an alternative, add a participant, and save the alternative choice on the user. This # method is guaranteed to only run once, and will skip the alternative choosing process if run # a second time. def choose!(context = nil) @user.cleanup_old_experiments! # Only run the process once return alternative if @alternative_chosen new_participant = @user[@experiment.key].nil? if override_is_alternative? self.alternative = @options[:override] if should_store_alternative? && !@user[@experiment.key] self.alternative.increment_participation end elsif @options[:disabled] || Split.configuration.disabled? self.alternative = @experiment.control elsif @experiment.has_winner? self.alternative = @experiment.winner else cleanup_old_versions if exclude_user? self.alternative = @experiment.control else self.alternative = @user[@experiment.key] if alternative.nil? if @experiment.cohorting_disabled? self.alternative = @experiment.control else self.alternative = @experiment.next_alternative # Increment the number of participants since we are actually choosing a new alternative self.alternative.increment_participation run_callback context, Split.configuration.on_trial_choose end end end end new_participant_and_cohorting_disabled = new_participant && @experiment.cohorting_disabled? @user[@experiment.key] = alternative.name unless @experiment.has_winner? || !should_store_alternative? || new_participant_and_cohorting_disabled @alternative_chosen = true run_callback context, Split.configuration.on_trial unless @options[:disabled] || Split.configuration.disabled? || new_participant_and_cohorting_disabled alternative end private def run_callback(context, callback_name) context.send(callback_name, self) if callback_name && context.respond_to?(callback_name, true) end def override_is_alternative? @experiment.alternatives.map(&:name).include?(@options[:override]) end def should_store_alternative? if @options[:override] || @options[:disabled] Split.configuration.store_override else !exclude_user? end end def cleanup_old_versions if @experiment.version > 0 @user.cleanup_old_versions!(@experiment) end end def exclude_user? @options[:exclude] || @experiment.start_time.nil? || @user.max_experiments_reached?(@experiment.key) end end end <MSG> Fix Layout/SpaceBeforeBlockBraces <DFF> @@ -32,7 +32,7 @@ module Split @alternative = if alternative.kind_of?(Split::Alternative) alternative else - @experiment.alternatives.find{|a| a.name == alternative } + @experiment.alternatives.find {|a| a.name == alternative } end end
1
Fix Layout/SpaceBeforeBlockBraces
1
.rb
rb
mit
splitrb/split
10072342
<NME> zscore.rb <BEF> # frozen_string_literal: true module Split class Zscore include Math def self.calculate(p1, n1, p2, n2) # p_1 = Pa = proportion of users who converted within the experiment split (conversion rate) # p_2 = Pc = proportion of users who converted within the control split (conversion rate) # n_1 = Na = the number of impressions within the experiment split # n_2 = Nc = the number of impressions within the control split # s_1 = SEa = standard error of p_1, the estiamte of the mean # s_2 = SEc = standard error of p_2, the estimate of the control # s_p = SEp = standard error of p_1 - p_2, assuming a pooled variance # s_unp = SEunp = standard error of p_1 - p_2, assuming unpooled variance p_1 = p1.to_f p_2 = p2.to_f n_1 = n1.to_f n_2 = n2.to_f # Perform checks on data to make sure we can validly run our confidence tests if n_1 < 30 || n_2 < 30 error = "Needs 30+ participants." return error elsif p_1 * n_1 < 5 || p_2 * n_2 < 5 error = "Needs 5+ conversions." return error end # Formula for standard error: root(pq/n) = root(p(1-p)/n) s_1 = Math.sqrt((p_1)*(1-p_1)/(n_1)) s_2 = Math.sqrt((p_2)*(1-p_2)/(n_2)) # Formula for pooled error of the difference of the means: root(π*(1-π)*(1/na+1/nc) # π = (xa + xc) / (na + nc) pi = (p_1*n_1 + p_2*n_2)/(n_1 + n_2) s_p = Math.sqrt(pi*(1-pi)*(1/n_1 + 1/n_2)) # Formula for unpooled error of the difference of the means: root(sa**2/na + sc**2/nc) s_unp = Math.sqrt(s_1**2 + s_2**2) # Boolean variable decides whether we can pool our variances pooled = s_1/s_2 < 2 && s_2/s_1 < 2 # Assign standard error either the pooled or unpooled variance se = pooled ? s_p : s_unp # Calculate z-score z_score = (p_1 - p_2)/(se) z_score end end end <MSG> Fix Layout/EmptyLinesAroundClassBody <DFF> @@ -2,7 +2,6 @@ module Split class Zscore - include Math def self.calculate(p1, n1, p2, n2)
0
Fix Layout/EmptyLinesAroundClassBody
1
.rb
rb
mit
splitrb/split
10072343
<NME> zscore.rb <BEF> # frozen_string_literal: true module Split class Zscore include Math def self.calculate(p1, n1, p2, n2) # p_1 = Pa = proportion of users who converted within the experiment split (conversion rate) # p_2 = Pc = proportion of users who converted within the control split (conversion rate) # n_1 = Na = the number of impressions within the experiment split # n_2 = Nc = the number of impressions within the control split # s_1 = SEa = standard error of p_1, the estiamte of the mean # s_2 = SEc = standard error of p_2, the estimate of the control # s_p = SEp = standard error of p_1 - p_2, assuming a pooled variance # s_unp = SEunp = standard error of p_1 - p_2, assuming unpooled variance p_1 = p1.to_f p_2 = p2.to_f n_1 = n1.to_f n_2 = n2.to_f # Perform checks on data to make sure we can validly run our confidence tests if n_1 < 30 || n_2 < 30 error = "Needs 30+ participants." return error elsif p_1 * n_1 < 5 || p_2 * n_2 < 5 error = "Needs 5+ conversions." return error end # Formula for standard error: root(pq/n) = root(p(1-p)/n) s_1 = Math.sqrt((p_1)*(1-p_1)/(n_1)) s_2 = Math.sqrt((p_2)*(1-p_2)/(n_2)) # Formula for pooled error of the difference of the means: root(π*(1-π)*(1/na+1/nc) # π = (xa + xc) / (na + nc) pi = (p_1*n_1 + p_2*n_2)/(n_1 + n_2) s_p = Math.sqrt(pi*(1-pi)*(1/n_1 + 1/n_2)) # Formula for unpooled error of the difference of the means: root(sa**2/na + sc**2/nc) s_unp = Math.sqrt(s_1**2 + s_2**2) # Boolean variable decides whether we can pool our variances pooled = s_1/s_2 < 2 && s_2/s_1 < 2 # Assign standard error either the pooled or unpooled variance se = pooled ? s_p : s_unp # Calculate z-score z_score = (p_1 - p_2)/(se) z_score end end end <MSG> Fix Layout/EmptyLinesAroundClassBody <DFF> @@ -2,7 +2,6 @@ module Split class Zscore - include Math def self.calculate(p1, n1, p2, n2)
0
Fix Layout/EmptyLinesAroundClassBody
1
.rb
rb
mit
splitrb/split
10072344
<NME> zscore.rb <BEF> # frozen_string_literal: true module Split class Zscore include Math def self.calculate(p1, n1, p2, n2) # p_1 = Pa = proportion of users who converted within the experiment split (conversion rate) # p_2 = Pc = proportion of users who converted within the control split (conversion rate) # n_1 = Na = the number of impressions within the experiment split # n_2 = Nc = the number of impressions within the control split # s_1 = SEa = standard error of p_1, the estiamte of the mean # s_2 = SEc = standard error of p_2, the estimate of the control # s_p = SEp = standard error of p_1 - p_2, assuming a pooled variance # s_unp = SEunp = standard error of p_1 - p_2, assuming unpooled variance p_1 = p1.to_f p_2 = p2.to_f n_1 = n1.to_f n_2 = n2.to_f # Perform checks on data to make sure we can validly run our confidence tests if n_1 < 30 || n_2 < 30 error = "Needs 30+ participants." return error elsif p_1 * n_1 < 5 || p_2 * n_2 < 5 error = "Needs 5+ conversions." return error end # Formula for standard error: root(pq/n) = root(p(1-p)/n) s_1 = Math.sqrt((p_1)*(1-p_1)/(n_1)) s_2 = Math.sqrt((p_2)*(1-p_2)/(n_2)) # Formula for pooled error of the difference of the means: root(π*(1-π)*(1/na+1/nc) # π = (xa + xc) / (na + nc) pi = (p_1*n_1 + p_2*n_2)/(n_1 + n_2) s_p = Math.sqrt(pi*(1-pi)*(1/n_1 + 1/n_2)) # Formula for unpooled error of the difference of the means: root(sa**2/na + sc**2/nc) s_unp = Math.sqrt(s_1**2 + s_2**2) # Boolean variable decides whether we can pool our variances pooled = s_1/s_2 < 2 && s_2/s_1 < 2 # Assign standard error either the pooled or unpooled variance se = pooled ? s_p : s_unp # Calculate z-score z_score = (p_1 - p_2)/(se) z_score end end end <MSG> Fix Layout/EmptyLinesAroundClassBody <DFF> @@ -2,7 +2,6 @@ module Split class Zscore - include Math def self.calculate(p1, n1, p2, n2)
0
Fix Layout/EmptyLinesAroundClassBody
1
.rb
rb
mit
splitrb/split
10072345
<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") }.should_not change { e.participant_count } end it "should return the given alternative for an existing user" do alternative = ab_test('link_color', 'blue', 'red') repeat_alternative = ab_test('link_color', 'blue', 'red') 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" 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> Adding posibility to start tests manually <DFF> @@ -71,6 +71,15 @@ describe Split::Helper do }.should_not change { e.participant_count } end + it 'should not increment the counter for an not started experiment' do + Split.configuration.stub(:start_manually => true) + e = Split::Experiment.find_or_create('button_size', 'small', 'big') + lambda { + a = ab_test('button_size', 'small', 'big') + a.should eq('small') + }.should_not change { e.participant_count } + end + it "should return the given alternative for an existing user" do alternative = ab_test('link_color', 'blue', 'red') repeat_alternative = ab_test('link_color', 'blue', 'red')
9
Adding posibility to start tests manually
0
.rb
rb
mit
splitrb/split
10072346
<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") }.should_not change { e.participant_count } end it "should return the given alternative for an existing user" do alternative = ab_test('link_color', 'blue', 'red') repeat_alternative = ab_test('link_color', 'blue', 'red') 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" 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> Adding posibility to start tests manually <DFF> @@ -71,6 +71,15 @@ describe Split::Helper do }.should_not change { e.participant_count } end + it 'should not increment the counter for an not started experiment' do + Split.configuration.stub(:start_manually => true) + e = Split::Experiment.find_or_create('button_size', 'small', 'big') + lambda { + a = ab_test('button_size', 'small', 'big') + a.should eq('small') + }.should_not change { e.participant_count } + end + it "should return the given alternative for an existing user" do alternative = ab_test('link_color', 'blue', 'red') repeat_alternative = ab_test('link_color', 'blue', 'red')
9
Adding posibility to start tests manually
0
.rb
rb
mit
splitrb/split
10072347
<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") }.should_not change { e.participant_count } end it "should return the given alternative for an existing user" do alternative = ab_test('link_color', 'blue', 'red') repeat_alternative = ab_test('link_color', 'blue', 'red') 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" 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> Adding posibility to start tests manually <DFF> @@ -71,6 +71,15 @@ describe Split::Helper do }.should_not change { e.participant_count } end + it 'should not increment the counter for an not started experiment' do + Split.configuration.stub(:start_manually => true) + e = Split::Experiment.find_or_create('button_size', 'small', 'big') + lambda { + a = ab_test('button_size', 'small', 'big') + a.should eq('small') + }.should_not change { e.participant_count } + end + it "should return the given alternative for an existing user" do alternative = ab_test('link_color', 'blue', 'red') repeat_alternative = ab_test('link_color', 'blue', 'red')
9
Adding posibility to start tests manually
0
.rb
rb
mit
splitrb/split
10072348
<NME> stylesheet.ts <BEF> 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', options: { 'output.field': (index, placeholder) => `\${${index}${placeholder ? ':' + placeholder : ''}}`, 'stylesheet.fuzzySearchMinScore': 0 snippets: { mten: 'margin: 10px;', fsz: 'font-size' } }); const snippets = parseStylesheetSnippets(defaultConfig.snippets); function expand(abbr: string, config = defaultConfig) { return expandAbbreviation(abbr, config, snippets); } describe('Stylesheet abbreviations', () => { 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'); it('numeric with format options', () => { const config = resolveConfig({ options: { 'stylesheet.intUnit': 'pt', 'stylesheet.floatUnit': 'vh', // 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};'); }); 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: ;'); }); it('CSS-in-JS', () => { const config = resolveConfig({ options: { 'stylesheet.json': true, 'stylesheet.between': ': ' it('functions', () => { equal(expand('trf-s(2)'), 'transform: scale(2, ${2:y});'); equal(expand('trf-s(2, 3)'), 'transform: scale(2, 3);'); }); it('resolve context value', () => { const config = resolveConfig({ context: { name: 'align-content' } }); 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> Allow `cache` object in config Emmet will store internal data in this object to improve performance across calls <DFF> @@ -1,5 +1,5 @@ import { strictEqual as equal, ok } from 'assert'; -import { stylesheet as expandAbbreviation, parseStylesheetSnippets, resolveConfig } from '../src'; +import { stylesheet as expandAbbreviation, resolveConfig } from '../src'; import score from '../src/stylesheet/score'; const defaultConfig = resolveConfig({ @@ -10,12 +10,12 @@ const defaultConfig = resolveConfig({ snippets: { mten: 'margin: 10px;', fsz: 'font-size' - } + }, + cache: {} }); -const snippets = parseStylesheetSnippets(defaultConfig.snippets); function expand(abbr: string, config = defaultConfig) { - return expandAbbreviation(abbr, config, snippets); + return expandAbbreviation(abbr, config); } describe('Stylesheet abbreviations', () => { @@ -105,6 +105,7 @@ describe('Stylesheet abbreviations', () => { it('numeric with format options', () => { const config = resolveConfig({ + type: 'stylesheet', options: { 'stylesheet.intUnit': 'pt', 'stylesheet.floatUnit': 'vh', @@ -157,12 +158,19 @@ describe('Stylesheet abbreviations', () => { }); 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('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', () => { const config = resolveConfig({ + type: 'stylesheet', options: { 'stylesheet.json': true, 'stylesheet.between': ': ' @@ -174,6 +182,7 @@ describe('Stylesheet abbreviations', () => { it('resolve context value', () => { const config = resolveConfig({ + type: 'stylesheet', context: { name: 'align-content' } });
15
Allow `cache` object in config
6
.ts
ts
mit
emmetio/emmet
10072349
<NME> stylesheet.ts <BEF> 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', options: { 'output.field': (index, placeholder) => `\${${index}${placeholder ? ':' + placeholder : ''}}`, 'stylesheet.fuzzySearchMinScore': 0 snippets: { mten: 'margin: 10px;', fsz: 'font-size' } }); const snippets = parseStylesheetSnippets(defaultConfig.snippets); function expand(abbr: string, config = defaultConfig) { return expandAbbreviation(abbr, config, snippets); } describe('Stylesheet abbreviations', () => { 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'); it('numeric with format options', () => { const config = resolveConfig({ options: { 'stylesheet.intUnit': 'pt', 'stylesheet.floatUnit': 'vh', // 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};'); }); 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: ;'); }); it('CSS-in-JS', () => { const config = resolveConfig({ options: { 'stylesheet.json': true, 'stylesheet.between': ': ' it('functions', () => { equal(expand('trf-s(2)'), 'transform: scale(2, ${2:y});'); equal(expand('trf-s(2, 3)'), 'transform: scale(2, 3);'); }); it('resolve context value', () => { const config = resolveConfig({ context: { name: 'align-content' } }); 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> Allow `cache` object in config Emmet will store internal data in this object to improve performance across calls <DFF> @@ -1,5 +1,5 @@ import { strictEqual as equal, ok } from 'assert'; -import { stylesheet as expandAbbreviation, parseStylesheetSnippets, resolveConfig } from '../src'; +import { stylesheet as expandAbbreviation, resolveConfig } from '../src'; import score from '../src/stylesheet/score'; const defaultConfig = resolveConfig({ @@ -10,12 +10,12 @@ const defaultConfig = resolveConfig({ snippets: { mten: 'margin: 10px;', fsz: 'font-size' - } + }, + cache: {} }); -const snippets = parseStylesheetSnippets(defaultConfig.snippets); function expand(abbr: string, config = defaultConfig) { - return expandAbbreviation(abbr, config, snippets); + return expandAbbreviation(abbr, config); } describe('Stylesheet abbreviations', () => { @@ -105,6 +105,7 @@ describe('Stylesheet abbreviations', () => { it('numeric with format options', () => { const config = resolveConfig({ + type: 'stylesheet', options: { 'stylesheet.intUnit': 'pt', 'stylesheet.floatUnit': 'vh', @@ -157,12 +158,19 @@ describe('Stylesheet abbreviations', () => { }); 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('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', () => { const config = resolveConfig({ + type: 'stylesheet', options: { 'stylesheet.json': true, 'stylesheet.between': ': ' @@ -174,6 +182,7 @@ describe('Stylesheet abbreviations', () => { it('resolve context value', () => { const config = resolveConfig({ + type: 'stylesheet', context: { name: 'align-content' } });
15
Allow `cache` object in config
6
.ts
ts
mit
emmetio/emmet