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
10072050
<NME> .npmignore <BEF> npm-debug.log* node_modules jspm_packages .npm /.* /*.* /test /src /packages <MSG> Exclude snippets from publishing <DFF> @@ -7,3 +7,4 @@ jspm_packages /test /src /packages +/snippets
1
Exclude snippets from publishing
0
npmignore
mit
emmetio/emmet
10072051
<NME> AUTHORS <BEF> Ask Solem <askh@opera.com> Rune Halvorsen <runeh@opera.com> Russell Sim <russell.sim@gmail.com> Brian Rosner <brosner@gmail.com> Hugo Lopes Tavares <hltbra@gmail.com> Sverre Johansen <sverre.johansen@gmail.com> Bo Shi <bs@alum.mit.edu> Carl Meyer <carl@dirtcircle.com> Vinícius das Chagas Silva <vinimaster@gmail.com> Vanderson Mota dos Santos <vanderson.mota@gmail.com> Stefan Foulis <stefan.foulis@gmail.com> Michael Richardson <michael@michaelrichardson.me> Halldor Brent Tubbs <brent.tubbs@gmail.com> David Cramer <dcramer@gmail.com> <MSG> Found full-name for contributor Halldor <DFF> @@ -10,4 +10,4 @@ Vinícius das Chagas Silva <vinimaster@gmail.com> Vanderson Mota dos Santos <vanderson.mota@gmail.com> Stefan Foulis <stefan.foulis@gmail.com> Michael Richardson <michael@michaelrichardson.me> -Halldor +Halldór Rúnarsson <halldor89@gmail.com>
1
Found full-name for contributor Halldor
1
AUTHORS
bsd-3-clause
ask/chishop
10072052
<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.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 'simple-random', '>= 0.9.3' s.add_development_dependency 'bundler', '~> 1.14' s.add_development_dependency 'simplecov', '~> 0.15' s.add_development_dependency 'rack-test', '~> 0.6' s.add_development_dependency 'rake', '~> 12' s.add_development_dependency "rspec", "~> 3.7" s.add_development_dependency "pry", "~> 0.10" s.add_development_dependency "rails", ">= 5.0" end <MSG> update bundler dev dependency <DFF> @@ -34,7 +34,7 @@ Gem::Specification.new do |s| s.add_dependency 'sinatra', '>= 1.2.6' s.add_dependency 'simple-random', '>= 0.9.3' - s.add_development_dependency 'bundler', '~> 1.14' + s.add_development_dependency 'bundler', '>= 1.17' s.add_development_dependency 'simplecov', '~> 0.15' s.add_development_dependency 'rack-test', '~> 0.6' s.add_development_dependency 'rake', '~> 12'
1
update bundler dev dependency
1
.gemspec
gemspec
mit
splitrb/split
10072053
<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.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 'simple-random', '>= 0.9.3' s.add_development_dependency 'bundler', '~> 1.14' s.add_development_dependency 'simplecov', '~> 0.15' s.add_development_dependency 'rack-test', '~> 0.6' s.add_development_dependency 'rake', '~> 12' s.add_development_dependency "rspec", "~> 3.7" s.add_development_dependency "pry", "~> 0.10" s.add_development_dependency "rails", ">= 5.0" end <MSG> update bundler dev dependency <DFF> @@ -34,7 +34,7 @@ Gem::Specification.new do |s| s.add_dependency 'sinatra', '>= 1.2.6' s.add_dependency 'simple-random', '>= 0.9.3' - s.add_development_dependency 'bundler', '~> 1.14' + s.add_development_dependency 'bundler', '>= 1.17' s.add_development_dependency 'simplecov', '~> 0.15' s.add_development_dependency 'rack-test', '~> 0.6' s.add_development_dependency 'rake', '~> 12'
1
update bundler dev dependency
1
.gemspec
gemspec
mit
splitrb/split
10072054
<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.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 'simple-random', '>= 0.9.3' s.add_development_dependency 'bundler', '~> 1.14' s.add_development_dependency 'simplecov', '~> 0.15' s.add_development_dependency 'rack-test', '~> 0.6' s.add_development_dependency 'rake', '~> 12' s.add_development_dependency "rspec", "~> 3.7" s.add_development_dependency "pry", "~> 0.10" s.add_development_dependency "rails", ">= 5.0" end <MSG> update bundler dev dependency <DFF> @@ -34,7 +34,7 @@ Gem::Specification.new do |s| s.add_dependency 'sinatra', '>= 1.2.6' s.add_dependency 'simple-random', '>= 0.9.3' - s.add_development_dependency 'bundler', '~> 1.14' + s.add_development_dependency 'bundler', '>= 1.17' s.add_development_dependency 'simplecov', '~> 0.15' s.add_development_dependency 'rack-test', '~> 0.6' s.add_development_dependency 'rake', '~> 12'
1
update bundler dev dependency
1
.gemspec
gemspec
mit
splitrb/split
10072055
<NME> encapsulated_helper_spec.rb <BEF> ADDFILE <MSG> #256 avoiding call to params in EncapsulatedHelper <DFF> @@ -0,0 +1,24 @@ +require 'spec_helper' + +describe Split::EncapsulatedHelper do + include Split::EncapsulatedHelper + + before do + @persistence_adapter = Split.configuration.persistence + Split.configuration.persistence = Hash + end + + after do + Split.configuration.persistence = @persistence_adapter + end + + def params + raise NoMethodError, 'This method is not really defined' + end + + describe "ab_test" do + it "should not raise an error when params raises an error" do + lambda { ab_test('link_color', 'blue', 'red') }.should_not raise_error + end + end +end
24
#256 avoiding call to params in EncapsulatedHelper
0
.rb
rb
mit
splitrb/split
10072056
<NME> encapsulated_helper_spec.rb <BEF> ADDFILE <MSG> #256 avoiding call to params in EncapsulatedHelper <DFF> @@ -0,0 +1,24 @@ +require 'spec_helper' + +describe Split::EncapsulatedHelper do + include Split::EncapsulatedHelper + + before do + @persistence_adapter = Split.configuration.persistence + Split.configuration.persistence = Hash + end + + after do + Split.configuration.persistence = @persistence_adapter + end + + def params + raise NoMethodError, 'This method is not really defined' + end + + describe "ab_test" do + it "should not raise an error when params raises an error" do + lambda { ab_test('link_color', 'blue', 'red') }.should_not raise_error + end + end +end
24
#256 avoiding call to params in EncapsulatedHelper
0
.rb
rb
mit
splitrb/split
10072057
<NME> encapsulated_helper_spec.rb <BEF> ADDFILE <MSG> #256 avoiding call to params in EncapsulatedHelper <DFF> @@ -0,0 +1,24 @@ +require 'spec_helper' + +describe Split::EncapsulatedHelper do + include Split::EncapsulatedHelper + + before do + @persistence_adapter = Split.configuration.persistence + Split.configuration.persistence = Hash + end + + after do + Split.configuration.persistence = @persistence_adapter + end + + def params + raise NoMethodError, 'This method is not really defined' + end + + describe "ab_test" do + it "should not raise an error when params raises an error" do + lambda { ab_test('link_color', 'blue', 'red') }.should_not raise_error + end + end +end
24
#256 avoiding call to params in EncapsulatedHelper
0
.rb
rb
mit
splitrb/split
10072058
<NME> helper_spec.rb <BEF> # frozen_string_literal: true require "spec_helper" # TODO change some of these tests to use Rack::Test describe Split::Helper do include Split::Helper let(:experiment) { Split::ExperimentCatalog.find_or_create("link_color", "blue", "red") } describe "ab_test" do it "should not raise an error when passed strings for alternatives" do expect { ab_test("xyz", "1", "2", "3") }.not_to raise_error end it "should not raise an error when passed an array for alternatives" do expect { ab_test("xyz", ["1", "2", "3"]) }.not_to raise_error end it "should raise the appropriate error when passed integers for alternatives" do expect { ab_test("xyz", 1, 2, 3) }.to raise_error(ArgumentError) end it "should raise the appropriate error when passed symbols for alternatives" do expect { ab_test("xyz", :a, :b, :c) }.to raise_error(ArgumentError) end it "should not raise error when passed an array for goals" do expect { ab_test({ "link_color" => ["purchase", "refund"] }, "blue", "red") }.not_to raise_error end it "should not raise error when passed just one goal" do expect { ab_test({ "link_color" => "purchase" }, "blue", "red") }.not_to raise_error end it "raises an appropriate error when processing combined expirements" do Split.configuration.experiments = { combined_exp_1: { alternatives: [ { name: "control", percent: 50 }, { name: "test-alt", percent: 50 } ], metric: :my_metric, combined_experiments: [:combined_exp_1_sub_1] } } Split::ExperimentCatalog.find_or_create("combined_exp_1") expect { ab_test("combined_exp_1") }.to raise_error(Split::InvalidExperimentsFormatError) end it "should assign a random alternative to a new user when there are an equal number of alternatives assigned" do ab_test("link_color", "blue", "red") expect(["red", "blue"]).to include(ab_user["link_color"]) end it "should increment the participation counter after assignment to a new user" do previous_red_count = Split::Alternative.new("red", "link_color").participant_count previous_blue_count = Split::Alternative.new("blue", "link_color").participant_count ab_test("link_color", "blue", "red") new_red_count = Split::Alternative.new("red", "link_color").participant_count new_blue_count = Split::Alternative.new("blue", "link_color").participant_count expect((new_red_count + new_blue_count)).to eq(previous_red_count + previous_blue_count + 1) end it "should not increment the counter for an experiment that the user is not participating in" do ab_test("link_color", "blue", "red") e = Split::ExperimentCatalog.find_or_create("button_size", "small", "big") expect { # User shouldn't participate in this second experiment ab_test("button_size", "small", "big") }.not_to change { e.participant_count } end it "should not increment the counter for an ended experiment" do e = Split::ExperimentCatalog.find_or_create("button_size", "small", "big") e.winner = "small" expect { a = ab_test("button_size", "small", "big") expect(a).to eq("small") }.not_to change { e.participant_count } end it "should not increment the counter for an not started experiment" do expect(Split.configuration).to receive(:start_manually).and_return(true) e = Split::ExperimentCatalog.find_or_create("button_size", "small", "big") expect { a = ab_test("button_size", "small", "big") expect(a).to eq("small") }.not_to change { e.participant_count } end it "should return the given alternative for an existing user" do expect(ab_test("link_color", "blue", "red")).to eq ab_test("link_color", "blue", "red") end it "should always return the winner if one is present" do experiment.winner = "orange" expect(ab_test("link_color", "blue", "red")).to eq("orange") end it "should allow the alternative to be forced by passing it in the params" do # ?ab_test[link_color]=blue @params = { "ab_test" => { "link_color" => "blue" } } alternative = ab_test("link_color", "blue", "red") expect(alternative).to eq("blue") alternative = ab_test("link_color", { "blue" => 1 }, "red" => 5) expect(alternative).to eq("blue") @params = { "ab_test" => { "link_color" => "red" } } alternative = ab_test("link_color", "blue", "red") expect(alternative).to eq("red") alternative = ab_test("link_color", { "blue" => 5 }, "red" => 1) expect(alternative).to eq("red") end it "should not allow an arbitrary alternative" do @params = { "ab_test" => { "link_color" => "pink" } } alternative = ab_test("link_color", "blue") expect(alternative).to eq("blue") end it "should not store the split when a param forced alternative" do @params = { "ab_test" => { "link_color" => "blue" } } expect(ab_user).not_to receive(:[]=) ab_test("link_color", "blue", "red") end it "SPLIT_DISABLE query parameter should also force the alternative (uses control)" do @params = { "SPLIT_DISABLE" => "true" } alternative = ab_test("link_color", "blue", "red") expect(alternative).to eq("blue") alternative = ab_test("link_color", { "blue" => 1 }, "red" => 5) expect(alternative).to eq("blue") alternative = ab_test("link_color", "red", "blue") expect(alternative).to eq("red") alternative = ab_test("link_color", { "red" => 5 }, "blue" => 1) expect(alternative).to eq("red") end it "should not store the split when Split generically disabled" do @params = { "SPLIT_DISABLE" => "true" } expect(ab_user).not_to receive(:[]=) ab_test("link_color", "blue", "red") end context "when store_override is set" do before { Split.configuration.store_override = true } it "should store the forced alternative" do @params = { "ab_test" => { "link_color" => "blue" } } expect(ab_user).to receive(:[]=).with("link_color", "blue") ab_test("link_color", "blue", "red") end end context "when on_trial_choose is set" do before { Split.configuration.on_trial_choose = :some_method } it "should call the method" do expect(self).to receive(:some_method) ab_test("link_color", "blue", "red") end end it "should allow passing a block" do alt = ab_test("link_color", "blue", "red") ret = ab_test("link_color", "blue", "red") { |alternative| "shared/#{alternative}" } expect(ret).to eq("shared/#{alt}") end it "should allow the share of visitors see an alternative to be specified" do ab_test("link_color", { "blue" => 0.8 }, { "red" => 20 }) expect(["red", "blue"]).to include(ab_user["link_color"]) end it "should allow alternative weighting interface as a single hash" do ab_test("link_color", { "blue" => 0.01 }, "red" => 0.2) experiment = Split::ExperimentCatalog.find("link_color") expect(experiment.alternatives.map(&:name)).to eq(["blue", "red"]) expect(experiment.alternatives.collect { |a| a.weight }).to match_array([0.01, 0.2]) end it "should only let a user participate in one experiment at a time" do link_color = ab_test("link_color", "blue", "red") ab_test("button_size", "small", "big") expect(ab_user["link_color"]).to eq(link_color) big = Split::Alternative.new("big", "button_size") expect(big.participant_count).to eq(0) small = Split::Alternative.new("small", "button_size") expect(small.participant_count).to eq(0) end it "should let a user participate in many experiment with allow_multiple_experiments option" do Split.configure do |config| config.allow_multiple_experiments = true end link_color = ab_test("link_color", "blue", "red") button_size = ab_test("button_size", "small", "big") expect(ab_user["link_color"]).to eq(link_color) expect(ab_user["button_size"]).to eq(button_size) button_size_alt = Split::Alternative.new(button_size, "button_size") expect(button_size_alt.participant_count).to eq(1) end context "with allow_multiple_experiments = 'control'" do it "should let a user participate in many experiment with one non-'control' alternative" do Split.configure do |config| config.allow_multiple_experiments = "control" end groups = 100.times.map do |n| ab_test("test#{n}".to_sym, { "control" => (100 - n) }, { "test#{n}-alt" => n }) end experiments = ab_user.active_experiments expect(experiments.size).to be > 1 count_control = experiments.values.count { |g| g == "control" } expect(count_control).to eq(experiments.size - 1) count_alts = groups.count { |g| g != "control" } expect(count_alts).to eq(1) end context "when user already has experiment" do let(:mock_user) { Split::User.new(self, { "test_0" => "test-alt" }) } before do Split.configure do |config| config.allow_multiple_experiments = "control" end Split::ExperimentCatalog.find_or_initialize("test_0", "control", "test-alt").save Split::ExperimentCatalog.find_or_initialize("test_1", "control", "test-alt").save end it "should restore previously selected alternative" do expect(ab_user.active_experiments.size).to eq 1 expect(ab_test(:test_0, { "control" => 100 }, { "test-alt" => 1 })).to eq "test-alt" expect(ab_test(:test_0, { "control" => 1 }, { "test-alt" => 100 })).to eq "test-alt" end it "should select the correct alternatives after experiment resets" do experiment = Split::ExperimentCatalog.find(:test_0) experiment.reset mock_user[experiment.key] = "test-alt" expect(ab_user.active_experiments.size).to eq 1 expect(ab_test(:test_0, { "control" => 100 }, { "test-alt" => 1 })).to eq "test-alt" expect(ab_test(:test_0, { "control" => 0 }, { "test-alt" => 100 })).to eq "test-alt" end it "lets override existing choice" do pending "this requires user store reset on first call not depending on whelther it is current trial" @params = { "ab_test" => { "test_1" => "test-alt" } } expect(ab_test(:test_0, { "control" => 0 }, { "test-alt" => 100 })).to eq "control" expect(ab_test(:test_1, { "control" => 100 }, { "test-alt" => 1 })).to eq "test-alt" end end end it "should not over-write a finished key when an experiment is on a later version" do experiment.increment_version ab_user = { experiment.key => "blue", experiment.finished_key => true } finished_session = ab_user.dup ab_test("link_color", "blue", "red") expect(ab_user).to eq(finished_session) end end describe "metadata" do context "is defined" do before do Split.configuration.experiments = { my_experiment: { alternatives: ["one", "two"], resettable: false, metadata: { "one" => "Meta1", "two" => "Meta2" } } } end it "should be passed to helper block" do @params = { "ab_test" => { "my_experiment" => "two" } } expect(ab_test("my_experiment")).to eq "two" expect(ab_test("my_experiment") do |alternative, meta| meta end).to eq("Meta2") end it "should pass control metadata helper block if library disabled" do Split.configure do |config| config.enabled = false end expect(ab_test("my_experiment")).to eq "one" expect(ab_test("my_experiment") do |_, meta| meta end).to eq("Meta1") end end context "is not defined" do before do Split.configuration.experiments = { my_experiment: { alternatives: ["one", "two"], resettable: false, metadata: nil } } context 'when redis is not available' do before(:each) do Split.stub(:redis).and_raise(Errno::ECONNREFUSED) end context 'and db_failover config option is turned off' do it "should pass control metadata helper block if library disabled" do Split.configure do |config| config.enabled = false end expect(ab_test("my_experiment") do |_, meta| meta end).to eq({}) end end end describe "ab_finished" do context "for an experiment that the user participates in" do before(:each) do @experiment_name = "link_color" @alternatives = ["blue", "red"] @experiment = Split::ExperimentCatalog.find_or_create(@experiment_name, *@alternatives) @alternative_name = ab_test(@experiment_name, *@alternatives) @previous_completion_count = Split::Alternative.new(@alternative_name, @experiment_name).completed_count end it "should increment the counter for the completed alternative" do ab_finished(@experiment_name) new_completion_count = Split::Alternative.new(@alternative_name, @experiment_name).completed_count expect(new_completion_count).to eq(@previous_completion_count + 1) end it "should set experiment's finished key if reset is false" do ab_finished(@experiment_name, { reset: false }) expect(ab_user[@experiment.key]).to eq(@alternative_name) expect(ab_user[@experiment.finished_key]).to eq(true) end it "should not increment the counter if reset is false and the experiment has been already finished" do 2.times { ab_finished(@experiment_name, { reset: false }) } new_completion_count = Split::Alternative.new(@alternative_name, @experiment_name).completed_count expect(new_completion_count).to eq(@previous_completion_count + 1) end it "should not increment the counter for an ended experiment" do e = Split::ExperimentCatalog.find_or_create("button_size", "small", "big") e.winner = "small" a = ab_test("button_size", "small", "big") expect(a).to eq("small") expect { ab_finished("button_size") }.not_to change { Split::Alternative.new(a, "button_size").completed_count } end it "should clear out the user's participation from their session" do expect(ab_user[@experiment.key]).to eq(@alternative_name) ab_finished(@experiment_name) expect(ab_user.keys).to be_empty end it "should not clear out the users session if reset is false" do expect(ab_user[@experiment.key]).to eq(@alternative_name) ab_finished(@experiment_name, { reset: false }) expect(ab_user[@experiment.key]).to eq(@alternative_name) expect(ab_user[@experiment.finished_key]).to eq(true) end it "should reset the users session when experiment is not versioned" do expect(ab_user[@experiment.key]).to eq(@alternative_name) ab_finished(@experiment_name) expect(ab_user.keys).to be_empty end it "should reset the users session when experiment is versioned" do @experiment.increment_version @alternative_name = ab_test(@experiment_name, *@alternatives) expect(ab_user[@experiment.key]).to eq(@alternative_name) ab_finished(@experiment_name) expect(ab_user.keys).to be_empty end context "when on_trial_complete is set" do before { Split.configuration.on_trial_complete = :some_method } it "should call the method" do expect(self).to receive(:some_method) ab_finished(@experiment_name) end it "should not call the method without alternative" do ab_user[@experiment.key] = nil expect(self).not_to receive(:some_method) ab_finished(@experiment_name) end end end context "for an experiment that the user is excluded from" do before do alternative = ab_test("link_color", "blue", "red") expect(Split::Alternative.new(alternative, "link_color").participant_count).to eq(1) alternative = ab_test("button_size", "small", "big") expect(Split::Alternative.new(alternative, "button_size").participant_count).to eq(0) end it "should not increment the completed counter" do # So, user should be participating in the link_color experiment and # receive the control for button_size. As the user is not participating in # the button size experiment, finishing it should not increase the # completion count for that alternative. expect { ab_finished("button_size") }.not_to change { Split::Alternative.new("small", "button_size").completed_count } end end context "for an experiment that the user does not participate in" do before do Split::ExperimentCatalog.find_or_create(:not_started_experiment, "control", "alt") end it "should not raise an exception" do expect { ab_finished(:not_started_experiment) }.not_to raise_exception end it "should not change the user state when reset is false" do expect { ab_finished(:not_started_experiment, reset: false) }.not_to change { ab_user.keys }.from([]) end it "should not change the user state when reset is true" do expect(self).not_to receive(:reset!) ab_finished(:not_started_experiment) end it "should not increment the completed counter" do ab_finished(:not_started_experiment) expect(Split::Alternative.new("control", :not_started_experiment).completed_count).to eq(0) expect(Split::Alternative.new("alt", :not_started_experiment).completed_count).to eq(0) end end end context "finished with config" do it "passes reset option" do Split.configuration.experiments = { my_experiment: { alternatives: ["one", "two"], resettable: false, } } alternative = ab_test(:my_experiment) experiment = Split::ExperimentCatalog.find :my_experiment ab_finished :my_experiment expect(ab_user[experiment.key]).to eq(alternative) expect(ab_user[experiment.finished_key]).to eq(true) end end context "finished with metric name" do before { Split.configuration.experiments = {} } before { expect(Split::Alternative).to receive(:new).at_least(1).times.and_call_original } def should_finish_experiment(experiment_name, should_finish = true) alts = Split.configuration.experiments[experiment_name][:alternatives] experiment = Split::ExperimentCatalog.find_or_create(experiment_name, *alts) alt_name = ab_user[experiment.key] = alts.first alt = double("alternative") expect(alt).to receive(:name).at_most(1).times.and_return(alt_name) expect(Split::Alternative).to receive(:new).at_most(1).times.with(alt_name, experiment_name.to_s).and_return(alt) if should_finish expect(alt).to receive(:increment_completion).at_most(1).times else expect(alt).not_to receive(:increment_completion) end end it "completes the test" do Split.configuration.experiments[:my_experiment] = { alternatives: [ "control_opt", "other_opt" ], metric: :my_metric } should_finish_experiment :my_experiment ab_finished :my_metric end it "completes all relevant tests" do Split.configuration.experiments = { exp_1: { alternatives: [ "1-1", "1-2" ], metric: :my_metric }, exp_2: { alternatives: [ "2-1", "2-2" ], metric: :another_metric }, exp_3: { alternatives: [ "3-1", "3-2" ], metric: :my_metric }, } should_finish_experiment :exp_1 should_finish_experiment :exp_2, false should_finish_experiment :exp_3 ab_finished :my_metric end it "passes reset option" do Split.configuration.experiments = { my_exp: { alternatives: ["one", "two"], metric: :my_metric, resettable: false, } } alternative_name = ab_test(:my_exp) exp = Split::ExperimentCatalog.find :my_exp ab_finished :my_metric expect(ab_user[exp.key]).to eq(alternative_name) expect(ab_user[exp.finished_key]).to be_truthy end it "passes through options" do Split.configuration.experiments = { my_exp: { alternatives: ["one", "two"], metric: :my_metric, } } alternative_name = ab_test(:my_exp) exp = Split::ExperimentCatalog.find :my_exp ab_finished :my_metric, reset: false expect(ab_user[exp.key]).to eq(alternative_name) expect(ab_user[exp.finished_key]).to be_truthy end end describe "conversions" do it "should return a conversion rate for an alternative" do alternative_name = ab_test("link_color", "blue", "red") previous_convertion_rate = Split::Alternative.new(alternative_name, "link_color").conversion_rate expect(previous_convertion_rate).to eq(0.0) ab_finished("link_color") new_convertion_rate = Split::Alternative.new(alternative_name, "link_color").conversion_rate expect(new_convertion_rate).to eq(1.0) end end describe "active experiments" do it "should show an active test" do alternative = ab_test("def", "4", "5", "6") expect(active_experiments.count).to eq 1 expect(active_experiments.first[0]).to eq "def" expect(active_experiments.first[1]).to eq alternative end it "should show a finished test" do alternative = ab_test("def", "4", "5", "6") ab_finished("def", { reset: false }) expect(active_experiments.count).to eq 1 expect(active_experiments.first[0]).to eq "def" expect(active_experiments.first[1]).to eq alternative end it "should show an active test when an experiment is on a later version" do experiment.reset expect(experiment.version).to eq(1) ab_test("link_color", "blue", "red") expect(active_experiments.count).to eq 1 expect(active_experiments.first[0]).to eq "link_color" end it "should show versioned tests properly" do 10.times { experiment.reset } alternative = ab_test(experiment.name, "blue", "red") ab_finished(experiment.name, reset: false) expect(experiment.version).to eq(10) expect(active_experiments.count).to eq 1 expect(active_experiments).to eq({ "link_color" => alternative }) end it "should show multiple tests" do Split.configure do |config| config.allow_multiple_experiments = true end alternative = ab_test("def", "4", "5", "6") another_alternative = ab_test("ghi", "7", "8", "9") expect(active_experiments.count).to eq 2 expect(active_experiments["def"]).to eq alternative expect(active_experiments["ghi"]).to eq another_alternative end it "should not show tests with winners" do Split.configure do |config| config.allow_multiple_experiments = true end e = Split::ExperimentCatalog.find_or_create("def", "4", "5", "6") e.winner = "4" ab_test("def", "4", "5", "6") another_alternative = ab_test("ghi", "7", "8", "9") expect(active_experiments.count).to eq 1 expect(active_experiments.first[0]).to eq "ghi" expect(active_experiments.first[1]).to eq another_alternative end end describe "when user is a robot" do before(:each) do @request = OpenStruct.new(user_agent: "Googlebot/2.1 (+http://www.google.com/bot.html)") end describe "ab_test" do it "should return the control" do alternative = ab_test("link_color", "blue", "red") expect(alternative).to eq experiment.control.name end it "should not create a experiment" do ab_test("link_color", "blue", "red") expect(Split::Experiment.new("link_color")).to be_a_new_record end it "should not increment the participation count" do previous_red_count = Split::Alternative.new("red", "link_color").participant_count previous_blue_count = Split::Alternative.new("blue", "link_color").participant_count ab_test("link_color", "blue", "red") new_red_count = Split::Alternative.new("red", "link_color").participant_count new_blue_count = Split::Alternative.new("blue", "link_color").participant_count expect((new_red_count + new_blue_count)).to eq(previous_red_count + previous_blue_count) end end describe "finished" do it "should not increment the completed count" do alternative_name = ab_test("link_color", "blue", "red") previous_completion_count = Split::Alternative.new(alternative_name, "link_color").completed_count ab_finished("link_color") new_completion_count = Split::Alternative.new(alternative_name, "link_color").completed_count expect(new_completion_count).to eq(previous_completion_count) end end end describe "when providing custom ignore logic" do context "using a proc to configure custom logic" do before(:each) do Split.configure do |c| c.ignore_filter = proc { |request| true } # ignore everything end end it "ignores the ab_test" do ab_test("link_color", "blue", "red") red_count = Split::Alternative.new("red", "link_color").participant_count blue_count = Split::Alternative.new("blue", "link_color").participant_count expect((red_count + blue_count)).to be(0) end end end shared_examples_for "a disabled test" do describe "ab_test" do it "should return the control" do alternative = ab_test("link_color", "blue", "red") expect(alternative).to eq experiment.control.name end it "should not increment the participation count" do previous_red_count = Split::Alternative.new("red", "link_color").participant_count previous_blue_count = Split::Alternative.new("blue", "link_color").participant_count ab_test("link_color", "blue", "red") new_red_count = Split::Alternative.new("red", "link_color").participant_count new_blue_count = Split::Alternative.new("blue", "link_color").participant_count expect((new_red_count + new_blue_count)).to eq(previous_red_count + previous_blue_count) end end describe "finished" do it "should not increment the completed count" do alternative_name = ab_test("link_color", "blue", "red") previous_completion_count = Split::Alternative.new(alternative_name, "link_color").completed_count ab_finished("link_color") new_completion_count = Split::Alternative.new(alternative_name, "link_color").completed_count expect(new_completion_count).to eq(previous_completion_count) end end end describe "when ip address is ignored" do context "individually" do before(:each) do @request = OpenStruct.new(ip: "81.19.48.130") Split.configure do |c| c.ignore_ip_addresses << "81.19.48.130" end end it_behaves_like "a disabled test" end context "for a range" do before(:each) do @request = OpenStruct.new(ip: "81.19.48.129") Split.configure do |c| c.ignore_ip_addresses << /81\.19\.48\.[0-9]+/ end end it_behaves_like "a disabled test" end context "using both a range and a specific value" do before(:each) do @request = OpenStruct.new(ip: "81.19.48.128") Split.configure do |c| c.ignore_ip_addresses << "81.19.48.130" c.ignore_ip_addresses << /81\.19\.48\.[0-9]+/ end end it_behaves_like "a disabled test" end context "when ignored other address" do before do @request = OpenStruct.new(ip: "1.1.1.1") Split.configure do |c| c.ignore_ip_addresses << "81.19.48.130" end end it "works as usual" do alternative_name = ab_test("link_color", "red", "blue") expect { ab_finished("link_color") }.to change(Split::Alternative.new(alternative_name, "link_color"), :completed_count).by(1) end end end describe "when user is previewing" do before(:each) do @request = OpenStruct.new(headers: { "x-purpose" => "preview" }) end it_behaves_like "a disabled test" end describe "versioned experiments" do it "should use version zero if no version is present" do alternative_name = ab_test("link_color", "blue", "red") expect(experiment.version).to eq(0) expect(ab_user["link_color"]).to eq(alternative_name) end it "should save the version of the experiment to the session" do experiment.reset expect(experiment.version).to eq(1) alternative_name = ab_test("link_color", "blue", "red") expect(ab_user["link_color:1"]).to eq(alternative_name) end it "should load the experiment even if the version is not 0" do experiment.reset expect(experiment.version).to eq(1) alternative_name = ab_test("link_color", "blue", "red") expect(ab_user["link_color:1"]).to eq(alternative_name) return_alternative_name = ab_test("link_color", "blue", "red") expect(return_alternative_name).to eq(alternative_name) end it "should reset the session of a user on an older version of the experiment" do alternative_name = ab_test("link_color", "blue", "red") expect(ab_user["link_color"]).to eq(alternative_name) alternative = Split::Alternative.new(alternative_name, "link_color") expect(alternative.participant_count).to eq(1) experiment.reset expect(experiment.version).to eq(1) alternative = Split::Alternative.new(alternative_name, "link_color") expect(alternative.participant_count).to eq(0) new_alternative_name = ab_test("link_color", "blue", "red") expect(ab_user["link_color:1"]).to eq(new_alternative_name) new_alternative = Split::Alternative.new(new_alternative_name, "link_color") expect(new_alternative.participant_count).to eq(1) end it "should cleanup old versions of experiments from the session" do alternative_name = ab_test("link_color", "blue", "red") expect(ab_user["link_color"]).to eq(alternative_name) alternative = Split::Alternative.new(alternative_name, "link_color") expect(alternative.participant_count).to eq(1) experiment.reset expect(experiment.version).to eq(1) alternative = Split::Alternative.new(alternative_name, "link_color") expect(alternative.participant_count).to eq(0) new_alternative_name = ab_test("link_color", "blue", "red") expect(ab_user["link_color:1"]).to eq(new_alternative_name) end it "should only count completion of users on the current version" do alternative_name = ab_test("link_color", "blue", "red") expect(ab_user["link_color"]).to eq(alternative_name) Split::Alternative.new(alternative_name, "link_color") experiment.reset expect(experiment.version).to eq(1) ab_finished("link_color") alternative = Split::Alternative.new(alternative_name, "link_color") expect(alternative.completed_count).to eq(0) end end context "when redis is not available" do before(:each) do expect(Split).to receive(:redis).at_most(5).times.and_raise(Errno::ECONNREFUSED.new) end context "and db_failover config option is turned off" do before(:each) do Split.configure do |config| config.db_failover = false end end describe "ab_test" do it "should raise an exception" do expect { ab_test("link_color", "blue", "red") }.to raise_error(Errno::ECONNREFUSED) end end describe "finished" do it "should raise an exception" do expect { ab_finished("link_color") }.to raise_error(Errno::ECONNREFUSED) end end describe "disable split testing" do before(:each) do Split.configure do |config| config.enabled = false end end it "should not attempt to connect to redis" do expect { ab_test("link_color", "blue", "red") }.not_to raise_error end it "should return control variable" do expect(ab_test("link_color", "blue", "red")).to eq("blue") expect { ab_finished("link_color") }.not_to raise_error end end end context "and db_failover config option is turned on" do before(:each) do Split.configure do |config| config.db_failover = true end end describe "ab_test" do it "should not raise an exception" do expect { ab_test("link_color", "blue", "red") }.not_to raise_error end it "should call db_failover_on_db_error proc with error as parameter" do Split.configure do |config| config.db_failover_on_db_error = proc do |error| expect(error).to be_a(Errno::ECONNREFUSED) end end expect(Split.configuration.db_failover_on_db_error).to receive(:call).and_call_original ab_test("link_color", "blue", "red") end it "should always use first alternative" do expect(ab_test("link_color", "blue", "red")).to eq("blue") expect(ab_test("link_color", { "blue" => 0.01 }, "red" => 0.2)).to eq("blue") expect(ab_test("link_color", { "blue" => 0.8 }, { "red" => 20 })).to eq("blue") expect(ab_test("link_color", "blue", "red") do |alternative| "shared/#{alternative}" end).to eq("shared/blue") end context "and db_failover_allow_parameter_override config option is turned on" do before(:each) do Split.configure do |config| config.db_failover_allow_parameter_override = true end end context "and given an override parameter" do it "should use given override instead of the first alternative" do @params = { "ab_test" => { "link_color" => "red" } } expect(ab_test("link_color", "blue", "red")).to eq("red") expect(ab_test("link_color", "blue", "red", "green")).to eq("red") expect(ab_test("link_color", { "blue" => 0.01 }, "red" => 0.2)).to eq("red") expect(ab_test("link_color", { "blue" => 0.8 }, { "red" => 20 })).to eq("red") expect(ab_test("link_color", "blue", "red") do |alternative| "shared/#{alternative}" end).to eq("shared/red") end end end context "and preloaded config given" do before do Split.configuration.experiments[:link_color] = { alternatives: [ "blue", "red" ], } end it "uses first alternative" do expect(ab_test(:link_color)).to eq("blue") end end end describe "finished" do it "should not raise an exception" do expect { ab_finished("link_color") }.not_to raise_error end it "should call db_failover_on_db_error proc with error as parameter" do Split.configure do |config| config.db_failover_on_db_error = proc do |error| expect(error).to be_a(Errno::ECONNREFUSED) end end expect(Split.configuration.db_failover_on_db_error).to receive(:call).and_call_original ab_finished("link_color") end end end end context "with preloaded config" do before { Split.configuration.experiments = {} } it "pulls options from config file" do Split.configuration.experiments[:my_experiment] = { alternatives: [ "control_opt", "other_opt" ], goals: ["goal1", "goal2"] } ab_test :my_experiment expect(Split::Experiment.new(:my_experiment).alternatives.map(&:name)).to eq([ "control_opt", "other_opt" ]) expect(Split::Experiment.new(:my_experiment).goals).to eq([ "goal1", "goal2" ]) end it "can be called multiple times" do Split.configuration.experiments[:my_experiment] = { alternatives: [ "control_opt", "other_opt" ], goals: ["goal1", "goal2"] } 5.times { ab_test :my_experiment } experiment = Split::Experiment.new(:my_experiment) expect(experiment.alternatives.map(&:name)).to eq([ "control_opt", "other_opt" ]) expect(experiment.goals).to eq([ "goal1", "goal2" ]) expect(experiment.participant_count).to eq(1) end it "accepts multiple goals" do Split.configuration.experiments[:my_experiment] = { alternatives: [ "control_opt", "other_opt" ], goals: [ "goal1", "goal2", "goal3" ] } ab_test :my_experiment experiment = Split::Experiment.new(:my_experiment) expect(experiment.goals).to eq([ "goal1", "goal2", "goal3" ]) end it "allow specifying goals to be optional" do Split.configuration.experiments[:my_experiment] = { alternatives: [ "control_opt", "other_opt" ] } experiment = Split::Experiment.new(:my_experiment) expect(experiment.goals).to eq([]) end it "accepts multiple alternatives" do Split.configuration.experiments[:my_experiment] = { alternatives: [ "control_opt", "second_opt", "third_opt" ], } ab_test :my_experiment experiment = Split::Experiment.new(:my_experiment) expect(experiment.alternatives.map(&:name)).to eq([ "control_opt", "second_opt", "third_opt" ]) end it "accepts probability on alternatives" do Split.configuration.experiments[:my_experiment] = { alternatives: [ { name: "control_opt", percent: 67 }, { name: "second_opt", percent: 10 }, { name: "third_opt", percent: 23 }, ], } ab_test :my_experiment experiment = Split::Experiment.new(:my_experiment) expect(experiment.alternatives.collect { |a| [a.name, a.weight] }).to eq([["control_opt", 0.67], ["second_opt", 0.1], ["third_opt", 0.23]]) end it "accepts probability on some alternatives" do Split.configuration.experiments[:my_experiment] = { alternatives: [ { name: "control_opt", percent: 34 }, "second_opt", { name: "third_opt", percent: 23 }, "fourth_opt", ], } ab_test :my_experiment experiment = Split::Experiment.new(:my_experiment) names_and_weights = experiment.alternatives.collect { |a| [a.name, a.weight] } expect(names_and_weights).to eq([["control_opt", 0.34], ["second_opt", 0.215], ["third_opt", 0.23], ["fourth_opt", 0.215]]) expect(names_and_weights.inject(0) { |sum, nw| sum + nw[1] }).to eq(1.0) end it "allows name param without probability" do Split.configuration.experiments[:my_experiment] = { alternatives: [ { name: "control_opt" }, "second_opt", { name: "third_opt", percent: 64 }, ], } ab_test :my_experiment experiment = Split::Experiment.new(:my_experiment) names_and_weights = experiment.alternatives.collect { |a| [a.name, a.weight] } expect(names_and_weights).to eq([["control_opt", 0.18], ["second_opt", 0.18], ["third_opt", 0.64]]) expect(names_and_weights.inject(0) { |sum, nw| sum + nw[1] }).to eq(1.0) end it "fails gracefully if config is missing experiment" do Split.configuration.experiments = { other_experiment: { foo: "Bar" } } expect { ab_test :my_experiment }.to raise_error(Split::ExperimentNotFound) end it "fails gracefully if config is missing" do expect { Split.configuration.experiments = nil }.to raise_error(Split::InvalidExperimentsFormatError) end it "fails gracefully if config is missing alternatives" do Split.configuration.experiments[:my_experiment] = { foo: "Bar" } expect { ab_test :my_experiment }.to raise_error(NoMethodError) end end it "should handle multiple experiments correctly" do experiment2 = Split::ExperimentCatalog.find_or_create("link_color2", "blue", "red") ab_test("link_color", "blue", "red") ab_test("link_color2", "blue", "red") ab_finished("link_color2") experiment2.alternatives.each do |alt| expect(alt.unfinished_count).to eq(0) end end context "with goals" do before do @experiment = { "link_color" => ["purchase", "refund"] } @alternatives = ["blue", "red"] @experiment_name, @goals = normalize_metric(@experiment) @goal1 = @goals[0] @goal2 = @goals[1] end it "should normalize experiment" do expect(@experiment_name).to eq("link_color") expect(@goals).to eq(["purchase", "refund"]) end describe "ab_test" do it "should allow experiment goals interface as a single hash" do ab_test(@experiment, *@alternatives) experiment = Split::ExperimentCatalog.find("link_color") expect(experiment.goals).to eq(["purchase", "refund"]) end end describe "ab_finished" do before do @alternative_name = ab_test(@experiment, *@alternatives) end it "should increment the counter for the specified-goal completed alternative" do expect { ab_finished({ "link_color" => ["purchase"] }) } .to change { Split::Alternative.new(@alternative_name, @experiment_name).completed_count(@goal2) }.by(0) .and change { Split::Alternative.new(@alternative_name, @experiment_name).completed_count(@goal1) }.by(1) end end end end <MSG> Merge pull request #53 from leocassarani/issue-52 Fix failing tests on Rubinius (issue #52) <DFF> @@ -319,7 +319,7 @@ describe Split::Helper do context 'when redis is not available' do before(:each) do - Split.stub(:redis).and_raise(Errno::ECONNREFUSED) + Split.stub(:redis).and_raise(Errno::ECONNREFUSED.new) end context 'and db_failover config option is turned off' do
1
Merge pull request #53 from leocassarani/issue-52
1
.rb
rb
mit
splitrb/split
10072059
<NME> helper_spec.rb <BEF> # frozen_string_literal: true require "spec_helper" # TODO change some of these tests to use Rack::Test describe Split::Helper do include Split::Helper let(:experiment) { Split::ExperimentCatalog.find_or_create("link_color", "blue", "red") } describe "ab_test" do it "should not raise an error when passed strings for alternatives" do expect { ab_test("xyz", "1", "2", "3") }.not_to raise_error end it "should not raise an error when passed an array for alternatives" do expect { ab_test("xyz", ["1", "2", "3"]) }.not_to raise_error end it "should raise the appropriate error when passed integers for alternatives" do expect { ab_test("xyz", 1, 2, 3) }.to raise_error(ArgumentError) end it "should raise the appropriate error when passed symbols for alternatives" do expect { ab_test("xyz", :a, :b, :c) }.to raise_error(ArgumentError) end it "should not raise error when passed an array for goals" do expect { ab_test({ "link_color" => ["purchase", "refund"] }, "blue", "red") }.not_to raise_error end it "should not raise error when passed just one goal" do expect { ab_test({ "link_color" => "purchase" }, "blue", "red") }.not_to raise_error end it "raises an appropriate error when processing combined expirements" do Split.configuration.experiments = { combined_exp_1: { alternatives: [ { name: "control", percent: 50 }, { name: "test-alt", percent: 50 } ], metric: :my_metric, combined_experiments: [:combined_exp_1_sub_1] } } Split::ExperimentCatalog.find_or_create("combined_exp_1") expect { ab_test("combined_exp_1") }.to raise_error(Split::InvalidExperimentsFormatError) end it "should assign a random alternative to a new user when there are an equal number of alternatives assigned" do ab_test("link_color", "blue", "red") expect(["red", "blue"]).to include(ab_user["link_color"]) end it "should increment the participation counter after assignment to a new user" do previous_red_count = Split::Alternative.new("red", "link_color").participant_count previous_blue_count = Split::Alternative.new("blue", "link_color").participant_count ab_test("link_color", "blue", "red") new_red_count = Split::Alternative.new("red", "link_color").participant_count new_blue_count = Split::Alternative.new("blue", "link_color").participant_count expect((new_red_count + new_blue_count)).to eq(previous_red_count + previous_blue_count + 1) end it "should not increment the counter for an experiment that the user is not participating in" do ab_test("link_color", "blue", "red") e = Split::ExperimentCatalog.find_or_create("button_size", "small", "big") expect { # User shouldn't participate in this second experiment ab_test("button_size", "small", "big") }.not_to change { e.participant_count } end it "should not increment the counter for an ended experiment" do e = Split::ExperimentCatalog.find_or_create("button_size", "small", "big") e.winner = "small" expect { a = ab_test("button_size", "small", "big") expect(a).to eq("small") }.not_to change { e.participant_count } end it "should not increment the counter for an not started experiment" do expect(Split.configuration).to receive(:start_manually).and_return(true) e = Split::ExperimentCatalog.find_or_create("button_size", "small", "big") expect { a = ab_test("button_size", "small", "big") expect(a).to eq("small") }.not_to change { e.participant_count } end it "should return the given alternative for an existing user" do expect(ab_test("link_color", "blue", "red")).to eq ab_test("link_color", "blue", "red") end it "should always return the winner if one is present" do experiment.winner = "orange" expect(ab_test("link_color", "blue", "red")).to eq("orange") end it "should allow the alternative to be forced by passing it in the params" do # ?ab_test[link_color]=blue @params = { "ab_test" => { "link_color" => "blue" } } alternative = ab_test("link_color", "blue", "red") expect(alternative).to eq("blue") alternative = ab_test("link_color", { "blue" => 1 }, "red" => 5) expect(alternative).to eq("blue") @params = { "ab_test" => { "link_color" => "red" } } alternative = ab_test("link_color", "blue", "red") expect(alternative).to eq("red") alternative = ab_test("link_color", { "blue" => 5 }, "red" => 1) expect(alternative).to eq("red") end it "should not allow an arbitrary alternative" do @params = { "ab_test" => { "link_color" => "pink" } } alternative = ab_test("link_color", "blue") expect(alternative).to eq("blue") end it "should not store the split when a param forced alternative" do @params = { "ab_test" => { "link_color" => "blue" } } expect(ab_user).not_to receive(:[]=) ab_test("link_color", "blue", "red") end it "SPLIT_DISABLE query parameter should also force the alternative (uses control)" do @params = { "SPLIT_DISABLE" => "true" } alternative = ab_test("link_color", "blue", "red") expect(alternative).to eq("blue") alternative = ab_test("link_color", { "blue" => 1 }, "red" => 5) expect(alternative).to eq("blue") alternative = ab_test("link_color", "red", "blue") expect(alternative).to eq("red") alternative = ab_test("link_color", { "red" => 5 }, "blue" => 1) expect(alternative).to eq("red") end it "should not store the split when Split generically disabled" do @params = { "SPLIT_DISABLE" => "true" } expect(ab_user).not_to receive(:[]=) ab_test("link_color", "blue", "red") end context "when store_override is set" do before { Split.configuration.store_override = true } it "should store the forced alternative" do @params = { "ab_test" => { "link_color" => "blue" } } expect(ab_user).to receive(:[]=).with("link_color", "blue") ab_test("link_color", "blue", "red") end end context "when on_trial_choose is set" do before { Split.configuration.on_trial_choose = :some_method } it "should call the method" do expect(self).to receive(:some_method) ab_test("link_color", "blue", "red") end end it "should allow passing a block" do alt = ab_test("link_color", "blue", "red") ret = ab_test("link_color", "blue", "red") { |alternative| "shared/#{alternative}" } expect(ret).to eq("shared/#{alt}") end it "should allow the share of visitors see an alternative to be specified" do ab_test("link_color", { "blue" => 0.8 }, { "red" => 20 }) expect(["red", "blue"]).to include(ab_user["link_color"]) end it "should allow alternative weighting interface as a single hash" do ab_test("link_color", { "blue" => 0.01 }, "red" => 0.2) experiment = Split::ExperimentCatalog.find("link_color") expect(experiment.alternatives.map(&:name)).to eq(["blue", "red"]) expect(experiment.alternatives.collect { |a| a.weight }).to match_array([0.01, 0.2]) end it "should only let a user participate in one experiment at a time" do link_color = ab_test("link_color", "blue", "red") ab_test("button_size", "small", "big") expect(ab_user["link_color"]).to eq(link_color) big = Split::Alternative.new("big", "button_size") expect(big.participant_count).to eq(0) small = Split::Alternative.new("small", "button_size") expect(small.participant_count).to eq(0) end it "should let a user participate in many experiment with allow_multiple_experiments option" do Split.configure do |config| config.allow_multiple_experiments = true end link_color = ab_test("link_color", "blue", "red") button_size = ab_test("button_size", "small", "big") expect(ab_user["link_color"]).to eq(link_color) expect(ab_user["button_size"]).to eq(button_size) button_size_alt = Split::Alternative.new(button_size, "button_size") expect(button_size_alt.participant_count).to eq(1) end context "with allow_multiple_experiments = 'control'" do it "should let a user participate in many experiment with one non-'control' alternative" do Split.configure do |config| config.allow_multiple_experiments = "control" end groups = 100.times.map do |n| ab_test("test#{n}".to_sym, { "control" => (100 - n) }, { "test#{n}-alt" => n }) end experiments = ab_user.active_experiments expect(experiments.size).to be > 1 count_control = experiments.values.count { |g| g == "control" } expect(count_control).to eq(experiments.size - 1) count_alts = groups.count { |g| g != "control" } expect(count_alts).to eq(1) end context "when user already has experiment" do let(:mock_user) { Split::User.new(self, { "test_0" => "test-alt" }) } before do Split.configure do |config| config.allow_multiple_experiments = "control" end Split::ExperimentCatalog.find_or_initialize("test_0", "control", "test-alt").save Split::ExperimentCatalog.find_or_initialize("test_1", "control", "test-alt").save end it "should restore previously selected alternative" do expect(ab_user.active_experiments.size).to eq 1 expect(ab_test(:test_0, { "control" => 100 }, { "test-alt" => 1 })).to eq "test-alt" expect(ab_test(:test_0, { "control" => 1 }, { "test-alt" => 100 })).to eq "test-alt" end it "should select the correct alternatives after experiment resets" do experiment = Split::ExperimentCatalog.find(:test_0) experiment.reset mock_user[experiment.key] = "test-alt" expect(ab_user.active_experiments.size).to eq 1 expect(ab_test(:test_0, { "control" => 100 }, { "test-alt" => 1 })).to eq "test-alt" expect(ab_test(:test_0, { "control" => 0 }, { "test-alt" => 100 })).to eq "test-alt" end it "lets override existing choice" do pending "this requires user store reset on first call not depending on whelther it is current trial" @params = { "ab_test" => { "test_1" => "test-alt" } } expect(ab_test(:test_0, { "control" => 0 }, { "test-alt" => 100 })).to eq "control" expect(ab_test(:test_1, { "control" => 100 }, { "test-alt" => 1 })).to eq "test-alt" end end end it "should not over-write a finished key when an experiment is on a later version" do experiment.increment_version ab_user = { experiment.key => "blue", experiment.finished_key => true } finished_session = ab_user.dup ab_test("link_color", "blue", "red") expect(ab_user).to eq(finished_session) end end describe "metadata" do context "is defined" do before do Split.configuration.experiments = { my_experiment: { alternatives: ["one", "two"], resettable: false, metadata: { "one" => "Meta1", "two" => "Meta2" } } } end it "should be passed to helper block" do @params = { "ab_test" => { "my_experiment" => "two" } } expect(ab_test("my_experiment")).to eq "two" expect(ab_test("my_experiment") do |alternative, meta| meta end).to eq("Meta2") end it "should pass control metadata helper block if library disabled" do Split.configure do |config| config.enabled = false end expect(ab_test("my_experiment")).to eq "one" expect(ab_test("my_experiment") do |_, meta| meta end).to eq("Meta1") end end context "is not defined" do before do Split.configuration.experiments = { my_experiment: { alternatives: ["one", "two"], resettable: false, metadata: nil } } context 'when redis is not available' do before(:each) do Split.stub(:redis).and_raise(Errno::ECONNREFUSED) end context 'and db_failover config option is turned off' do it "should pass control metadata helper block if library disabled" do Split.configure do |config| config.enabled = false end expect(ab_test("my_experiment") do |_, meta| meta end).to eq({}) end end end describe "ab_finished" do context "for an experiment that the user participates in" do before(:each) do @experiment_name = "link_color" @alternatives = ["blue", "red"] @experiment = Split::ExperimentCatalog.find_or_create(@experiment_name, *@alternatives) @alternative_name = ab_test(@experiment_name, *@alternatives) @previous_completion_count = Split::Alternative.new(@alternative_name, @experiment_name).completed_count end it "should increment the counter for the completed alternative" do ab_finished(@experiment_name) new_completion_count = Split::Alternative.new(@alternative_name, @experiment_name).completed_count expect(new_completion_count).to eq(@previous_completion_count + 1) end it "should set experiment's finished key if reset is false" do ab_finished(@experiment_name, { reset: false }) expect(ab_user[@experiment.key]).to eq(@alternative_name) expect(ab_user[@experiment.finished_key]).to eq(true) end it "should not increment the counter if reset is false and the experiment has been already finished" do 2.times { ab_finished(@experiment_name, { reset: false }) } new_completion_count = Split::Alternative.new(@alternative_name, @experiment_name).completed_count expect(new_completion_count).to eq(@previous_completion_count + 1) end it "should not increment the counter for an ended experiment" do e = Split::ExperimentCatalog.find_or_create("button_size", "small", "big") e.winner = "small" a = ab_test("button_size", "small", "big") expect(a).to eq("small") expect { ab_finished("button_size") }.not_to change { Split::Alternative.new(a, "button_size").completed_count } end it "should clear out the user's participation from their session" do expect(ab_user[@experiment.key]).to eq(@alternative_name) ab_finished(@experiment_name) expect(ab_user.keys).to be_empty end it "should not clear out the users session if reset is false" do expect(ab_user[@experiment.key]).to eq(@alternative_name) ab_finished(@experiment_name, { reset: false }) expect(ab_user[@experiment.key]).to eq(@alternative_name) expect(ab_user[@experiment.finished_key]).to eq(true) end it "should reset the users session when experiment is not versioned" do expect(ab_user[@experiment.key]).to eq(@alternative_name) ab_finished(@experiment_name) expect(ab_user.keys).to be_empty end it "should reset the users session when experiment is versioned" do @experiment.increment_version @alternative_name = ab_test(@experiment_name, *@alternatives) expect(ab_user[@experiment.key]).to eq(@alternative_name) ab_finished(@experiment_name) expect(ab_user.keys).to be_empty end context "when on_trial_complete is set" do before { Split.configuration.on_trial_complete = :some_method } it "should call the method" do expect(self).to receive(:some_method) ab_finished(@experiment_name) end it "should not call the method without alternative" do ab_user[@experiment.key] = nil expect(self).not_to receive(:some_method) ab_finished(@experiment_name) end end end context "for an experiment that the user is excluded from" do before do alternative = ab_test("link_color", "blue", "red") expect(Split::Alternative.new(alternative, "link_color").participant_count).to eq(1) alternative = ab_test("button_size", "small", "big") expect(Split::Alternative.new(alternative, "button_size").participant_count).to eq(0) end it "should not increment the completed counter" do # So, user should be participating in the link_color experiment and # receive the control for button_size. As the user is not participating in # the button size experiment, finishing it should not increase the # completion count for that alternative. expect { ab_finished("button_size") }.not_to change { Split::Alternative.new("small", "button_size").completed_count } end end context "for an experiment that the user does not participate in" do before do Split::ExperimentCatalog.find_or_create(:not_started_experiment, "control", "alt") end it "should not raise an exception" do expect { ab_finished(:not_started_experiment) }.not_to raise_exception end it "should not change the user state when reset is false" do expect { ab_finished(:not_started_experiment, reset: false) }.not_to change { ab_user.keys }.from([]) end it "should not change the user state when reset is true" do expect(self).not_to receive(:reset!) ab_finished(:not_started_experiment) end it "should not increment the completed counter" do ab_finished(:not_started_experiment) expect(Split::Alternative.new("control", :not_started_experiment).completed_count).to eq(0) expect(Split::Alternative.new("alt", :not_started_experiment).completed_count).to eq(0) end end end context "finished with config" do it "passes reset option" do Split.configuration.experiments = { my_experiment: { alternatives: ["one", "two"], resettable: false, } } alternative = ab_test(:my_experiment) experiment = Split::ExperimentCatalog.find :my_experiment ab_finished :my_experiment expect(ab_user[experiment.key]).to eq(alternative) expect(ab_user[experiment.finished_key]).to eq(true) end end context "finished with metric name" do before { Split.configuration.experiments = {} } before { expect(Split::Alternative).to receive(:new).at_least(1).times.and_call_original } def should_finish_experiment(experiment_name, should_finish = true) alts = Split.configuration.experiments[experiment_name][:alternatives] experiment = Split::ExperimentCatalog.find_or_create(experiment_name, *alts) alt_name = ab_user[experiment.key] = alts.first alt = double("alternative") expect(alt).to receive(:name).at_most(1).times.and_return(alt_name) expect(Split::Alternative).to receive(:new).at_most(1).times.with(alt_name, experiment_name.to_s).and_return(alt) if should_finish expect(alt).to receive(:increment_completion).at_most(1).times else expect(alt).not_to receive(:increment_completion) end end it "completes the test" do Split.configuration.experiments[:my_experiment] = { alternatives: [ "control_opt", "other_opt" ], metric: :my_metric } should_finish_experiment :my_experiment ab_finished :my_metric end it "completes all relevant tests" do Split.configuration.experiments = { exp_1: { alternatives: [ "1-1", "1-2" ], metric: :my_metric }, exp_2: { alternatives: [ "2-1", "2-2" ], metric: :another_metric }, exp_3: { alternatives: [ "3-1", "3-2" ], metric: :my_metric }, } should_finish_experiment :exp_1 should_finish_experiment :exp_2, false should_finish_experiment :exp_3 ab_finished :my_metric end it "passes reset option" do Split.configuration.experiments = { my_exp: { alternatives: ["one", "two"], metric: :my_metric, resettable: false, } } alternative_name = ab_test(:my_exp) exp = Split::ExperimentCatalog.find :my_exp ab_finished :my_metric expect(ab_user[exp.key]).to eq(alternative_name) expect(ab_user[exp.finished_key]).to be_truthy end it "passes through options" do Split.configuration.experiments = { my_exp: { alternatives: ["one", "two"], metric: :my_metric, } } alternative_name = ab_test(:my_exp) exp = Split::ExperimentCatalog.find :my_exp ab_finished :my_metric, reset: false expect(ab_user[exp.key]).to eq(alternative_name) expect(ab_user[exp.finished_key]).to be_truthy end end describe "conversions" do it "should return a conversion rate for an alternative" do alternative_name = ab_test("link_color", "blue", "red") previous_convertion_rate = Split::Alternative.new(alternative_name, "link_color").conversion_rate expect(previous_convertion_rate).to eq(0.0) ab_finished("link_color") new_convertion_rate = Split::Alternative.new(alternative_name, "link_color").conversion_rate expect(new_convertion_rate).to eq(1.0) end end describe "active experiments" do it "should show an active test" do alternative = ab_test("def", "4", "5", "6") expect(active_experiments.count).to eq 1 expect(active_experiments.first[0]).to eq "def" expect(active_experiments.first[1]).to eq alternative end it "should show a finished test" do alternative = ab_test("def", "4", "5", "6") ab_finished("def", { reset: false }) expect(active_experiments.count).to eq 1 expect(active_experiments.first[0]).to eq "def" expect(active_experiments.first[1]).to eq alternative end it "should show an active test when an experiment is on a later version" do experiment.reset expect(experiment.version).to eq(1) ab_test("link_color", "blue", "red") expect(active_experiments.count).to eq 1 expect(active_experiments.first[0]).to eq "link_color" end it "should show versioned tests properly" do 10.times { experiment.reset } alternative = ab_test(experiment.name, "blue", "red") ab_finished(experiment.name, reset: false) expect(experiment.version).to eq(10) expect(active_experiments.count).to eq 1 expect(active_experiments).to eq({ "link_color" => alternative }) end it "should show multiple tests" do Split.configure do |config| config.allow_multiple_experiments = true end alternative = ab_test("def", "4", "5", "6") another_alternative = ab_test("ghi", "7", "8", "9") expect(active_experiments.count).to eq 2 expect(active_experiments["def"]).to eq alternative expect(active_experiments["ghi"]).to eq another_alternative end it "should not show tests with winners" do Split.configure do |config| config.allow_multiple_experiments = true end e = Split::ExperimentCatalog.find_or_create("def", "4", "5", "6") e.winner = "4" ab_test("def", "4", "5", "6") another_alternative = ab_test("ghi", "7", "8", "9") expect(active_experiments.count).to eq 1 expect(active_experiments.first[0]).to eq "ghi" expect(active_experiments.first[1]).to eq another_alternative end end describe "when user is a robot" do before(:each) do @request = OpenStruct.new(user_agent: "Googlebot/2.1 (+http://www.google.com/bot.html)") end describe "ab_test" do it "should return the control" do alternative = ab_test("link_color", "blue", "red") expect(alternative).to eq experiment.control.name end it "should not create a experiment" do ab_test("link_color", "blue", "red") expect(Split::Experiment.new("link_color")).to be_a_new_record end it "should not increment the participation count" do previous_red_count = Split::Alternative.new("red", "link_color").participant_count previous_blue_count = Split::Alternative.new("blue", "link_color").participant_count ab_test("link_color", "blue", "red") new_red_count = Split::Alternative.new("red", "link_color").participant_count new_blue_count = Split::Alternative.new("blue", "link_color").participant_count expect((new_red_count + new_blue_count)).to eq(previous_red_count + previous_blue_count) end end describe "finished" do it "should not increment the completed count" do alternative_name = ab_test("link_color", "blue", "red") previous_completion_count = Split::Alternative.new(alternative_name, "link_color").completed_count ab_finished("link_color") new_completion_count = Split::Alternative.new(alternative_name, "link_color").completed_count expect(new_completion_count).to eq(previous_completion_count) end end end describe "when providing custom ignore logic" do context "using a proc to configure custom logic" do before(:each) do Split.configure do |c| c.ignore_filter = proc { |request| true } # ignore everything end end it "ignores the ab_test" do ab_test("link_color", "blue", "red") red_count = Split::Alternative.new("red", "link_color").participant_count blue_count = Split::Alternative.new("blue", "link_color").participant_count expect((red_count + blue_count)).to be(0) end end end shared_examples_for "a disabled test" do describe "ab_test" do it "should return the control" do alternative = ab_test("link_color", "blue", "red") expect(alternative).to eq experiment.control.name end it "should not increment the participation count" do previous_red_count = Split::Alternative.new("red", "link_color").participant_count previous_blue_count = Split::Alternative.new("blue", "link_color").participant_count ab_test("link_color", "blue", "red") new_red_count = Split::Alternative.new("red", "link_color").participant_count new_blue_count = Split::Alternative.new("blue", "link_color").participant_count expect((new_red_count + new_blue_count)).to eq(previous_red_count + previous_blue_count) end end describe "finished" do it "should not increment the completed count" do alternative_name = ab_test("link_color", "blue", "red") previous_completion_count = Split::Alternative.new(alternative_name, "link_color").completed_count ab_finished("link_color") new_completion_count = Split::Alternative.new(alternative_name, "link_color").completed_count expect(new_completion_count).to eq(previous_completion_count) end end end describe "when ip address is ignored" do context "individually" do before(:each) do @request = OpenStruct.new(ip: "81.19.48.130") Split.configure do |c| c.ignore_ip_addresses << "81.19.48.130" end end it_behaves_like "a disabled test" end context "for a range" do before(:each) do @request = OpenStruct.new(ip: "81.19.48.129") Split.configure do |c| c.ignore_ip_addresses << /81\.19\.48\.[0-9]+/ end end it_behaves_like "a disabled test" end context "using both a range and a specific value" do before(:each) do @request = OpenStruct.new(ip: "81.19.48.128") Split.configure do |c| c.ignore_ip_addresses << "81.19.48.130" c.ignore_ip_addresses << /81\.19\.48\.[0-9]+/ end end it_behaves_like "a disabled test" end context "when ignored other address" do before do @request = OpenStruct.new(ip: "1.1.1.1") Split.configure do |c| c.ignore_ip_addresses << "81.19.48.130" end end it "works as usual" do alternative_name = ab_test("link_color", "red", "blue") expect { ab_finished("link_color") }.to change(Split::Alternative.new(alternative_name, "link_color"), :completed_count).by(1) end end end describe "when user is previewing" do before(:each) do @request = OpenStruct.new(headers: { "x-purpose" => "preview" }) end it_behaves_like "a disabled test" end describe "versioned experiments" do it "should use version zero if no version is present" do alternative_name = ab_test("link_color", "blue", "red") expect(experiment.version).to eq(0) expect(ab_user["link_color"]).to eq(alternative_name) end it "should save the version of the experiment to the session" do experiment.reset expect(experiment.version).to eq(1) alternative_name = ab_test("link_color", "blue", "red") expect(ab_user["link_color:1"]).to eq(alternative_name) end it "should load the experiment even if the version is not 0" do experiment.reset expect(experiment.version).to eq(1) alternative_name = ab_test("link_color", "blue", "red") expect(ab_user["link_color:1"]).to eq(alternative_name) return_alternative_name = ab_test("link_color", "blue", "red") expect(return_alternative_name).to eq(alternative_name) end it "should reset the session of a user on an older version of the experiment" do alternative_name = ab_test("link_color", "blue", "red") expect(ab_user["link_color"]).to eq(alternative_name) alternative = Split::Alternative.new(alternative_name, "link_color") expect(alternative.participant_count).to eq(1) experiment.reset expect(experiment.version).to eq(1) alternative = Split::Alternative.new(alternative_name, "link_color") expect(alternative.participant_count).to eq(0) new_alternative_name = ab_test("link_color", "blue", "red") expect(ab_user["link_color:1"]).to eq(new_alternative_name) new_alternative = Split::Alternative.new(new_alternative_name, "link_color") expect(new_alternative.participant_count).to eq(1) end it "should cleanup old versions of experiments from the session" do alternative_name = ab_test("link_color", "blue", "red") expect(ab_user["link_color"]).to eq(alternative_name) alternative = Split::Alternative.new(alternative_name, "link_color") expect(alternative.participant_count).to eq(1) experiment.reset expect(experiment.version).to eq(1) alternative = Split::Alternative.new(alternative_name, "link_color") expect(alternative.participant_count).to eq(0) new_alternative_name = ab_test("link_color", "blue", "red") expect(ab_user["link_color:1"]).to eq(new_alternative_name) end it "should only count completion of users on the current version" do alternative_name = ab_test("link_color", "blue", "red") expect(ab_user["link_color"]).to eq(alternative_name) Split::Alternative.new(alternative_name, "link_color") experiment.reset expect(experiment.version).to eq(1) ab_finished("link_color") alternative = Split::Alternative.new(alternative_name, "link_color") expect(alternative.completed_count).to eq(0) end end context "when redis is not available" do before(:each) do expect(Split).to receive(:redis).at_most(5).times.and_raise(Errno::ECONNREFUSED.new) end context "and db_failover config option is turned off" do before(:each) do Split.configure do |config| config.db_failover = false end end describe "ab_test" do it "should raise an exception" do expect { ab_test("link_color", "blue", "red") }.to raise_error(Errno::ECONNREFUSED) end end describe "finished" do it "should raise an exception" do expect { ab_finished("link_color") }.to raise_error(Errno::ECONNREFUSED) end end describe "disable split testing" do before(:each) do Split.configure do |config| config.enabled = false end end it "should not attempt to connect to redis" do expect { ab_test("link_color", "blue", "red") }.not_to raise_error end it "should return control variable" do expect(ab_test("link_color", "blue", "red")).to eq("blue") expect { ab_finished("link_color") }.not_to raise_error end end end context "and db_failover config option is turned on" do before(:each) do Split.configure do |config| config.db_failover = true end end describe "ab_test" do it "should not raise an exception" do expect { ab_test("link_color", "blue", "red") }.not_to raise_error end it "should call db_failover_on_db_error proc with error as parameter" do Split.configure do |config| config.db_failover_on_db_error = proc do |error| expect(error).to be_a(Errno::ECONNREFUSED) end end expect(Split.configuration.db_failover_on_db_error).to receive(:call).and_call_original ab_test("link_color", "blue", "red") end it "should always use first alternative" do expect(ab_test("link_color", "blue", "red")).to eq("blue") expect(ab_test("link_color", { "blue" => 0.01 }, "red" => 0.2)).to eq("blue") expect(ab_test("link_color", { "blue" => 0.8 }, { "red" => 20 })).to eq("blue") expect(ab_test("link_color", "blue", "red") do |alternative| "shared/#{alternative}" end).to eq("shared/blue") end context "and db_failover_allow_parameter_override config option is turned on" do before(:each) do Split.configure do |config| config.db_failover_allow_parameter_override = true end end context "and given an override parameter" do it "should use given override instead of the first alternative" do @params = { "ab_test" => { "link_color" => "red" } } expect(ab_test("link_color", "blue", "red")).to eq("red") expect(ab_test("link_color", "blue", "red", "green")).to eq("red") expect(ab_test("link_color", { "blue" => 0.01 }, "red" => 0.2)).to eq("red") expect(ab_test("link_color", { "blue" => 0.8 }, { "red" => 20 })).to eq("red") expect(ab_test("link_color", "blue", "red") do |alternative| "shared/#{alternative}" end).to eq("shared/red") end end end context "and preloaded config given" do before do Split.configuration.experiments[:link_color] = { alternatives: [ "blue", "red" ], } end it "uses first alternative" do expect(ab_test(:link_color)).to eq("blue") end end end describe "finished" do it "should not raise an exception" do expect { ab_finished("link_color") }.not_to raise_error end it "should call db_failover_on_db_error proc with error as parameter" do Split.configure do |config| config.db_failover_on_db_error = proc do |error| expect(error).to be_a(Errno::ECONNREFUSED) end end expect(Split.configuration.db_failover_on_db_error).to receive(:call).and_call_original ab_finished("link_color") end end end end context "with preloaded config" do before { Split.configuration.experiments = {} } it "pulls options from config file" do Split.configuration.experiments[:my_experiment] = { alternatives: [ "control_opt", "other_opt" ], goals: ["goal1", "goal2"] } ab_test :my_experiment expect(Split::Experiment.new(:my_experiment).alternatives.map(&:name)).to eq([ "control_opt", "other_opt" ]) expect(Split::Experiment.new(:my_experiment).goals).to eq([ "goal1", "goal2" ]) end it "can be called multiple times" do Split.configuration.experiments[:my_experiment] = { alternatives: [ "control_opt", "other_opt" ], goals: ["goal1", "goal2"] } 5.times { ab_test :my_experiment } experiment = Split::Experiment.new(:my_experiment) expect(experiment.alternatives.map(&:name)).to eq([ "control_opt", "other_opt" ]) expect(experiment.goals).to eq([ "goal1", "goal2" ]) expect(experiment.participant_count).to eq(1) end it "accepts multiple goals" do Split.configuration.experiments[:my_experiment] = { alternatives: [ "control_opt", "other_opt" ], goals: [ "goal1", "goal2", "goal3" ] } ab_test :my_experiment experiment = Split::Experiment.new(:my_experiment) expect(experiment.goals).to eq([ "goal1", "goal2", "goal3" ]) end it "allow specifying goals to be optional" do Split.configuration.experiments[:my_experiment] = { alternatives: [ "control_opt", "other_opt" ] } experiment = Split::Experiment.new(:my_experiment) expect(experiment.goals).to eq([]) end it "accepts multiple alternatives" do Split.configuration.experiments[:my_experiment] = { alternatives: [ "control_opt", "second_opt", "third_opt" ], } ab_test :my_experiment experiment = Split::Experiment.new(:my_experiment) expect(experiment.alternatives.map(&:name)).to eq([ "control_opt", "second_opt", "third_opt" ]) end it "accepts probability on alternatives" do Split.configuration.experiments[:my_experiment] = { alternatives: [ { name: "control_opt", percent: 67 }, { name: "second_opt", percent: 10 }, { name: "third_opt", percent: 23 }, ], } ab_test :my_experiment experiment = Split::Experiment.new(:my_experiment) expect(experiment.alternatives.collect { |a| [a.name, a.weight] }).to eq([["control_opt", 0.67], ["second_opt", 0.1], ["third_opt", 0.23]]) end it "accepts probability on some alternatives" do Split.configuration.experiments[:my_experiment] = { alternatives: [ { name: "control_opt", percent: 34 }, "second_opt", { name: "third_opt", percent: 23 }, "fourth_opt", ], } ab_test :my_experiment experiment = Split::Experiment.new(:my_experiment) names_and_weights = experiment.alternatives.collect { |a| [a.name, a.weight] } expect(names_and_weights).to eq([["control_opt", 0.34], ["second_opt", 0.215], ["third_opt", 0.23], ["fourth_opt", 0.215]]) expect(names_and_weights.inject(0) { |sum, nw| sum + nw[1] }).to eq(1.0) end it "allows name param without probability" do Split.configuration.experiments[:my_experiment] = { alternatives: [ { name: "control_opt" }, "second_opt", { name: "third_opt", percent: 64 }, ], } ab_test :my_experiment experiment = Split::Experiment.new(:my_experiment) names_and_weights = experiment.alternatives.collect { |a| [a.name, a.weight] } expect(names_and_weights).to eq([["control_opt", 0.18], ["second_opt", 0.18], ["third_opt", 0.64]]) expect(names_and_weights.inject(0) { |sum, nw| sum + nw[1] }).to eq(1.0) end it "fails gracefully if config is missing experiment" do Split.configuration.experiments = { other_experiment: { foo: "Bar" } } expect { ab_test :my_experiment }.to raise_error(Split::ExperimentNotFound) end it "fails gracefully if config is missing" do expect { Split.configuration.experiments = nil }.to raise_error(Split::InvalidExperimentsFormatError) end it "fails gracefully if config is missing alternatives" do Split.configuration.experiments[:my_experiment] = { foo: "Bar" } expect { ab_test :my_experiment }.to raise_error(NoMethodError) end end it "should handle multiple experiments correctly" do experiment2 = Split::ExperimentCatalog.find_or_create("link_color2", "blue", "red") ab_test("link_color", "blue", "red") ab_test("link_color2", "blue", "red") ab_finished("link_color2") experiment2.alternatives.each do |alt| expect(alt.unfinished_count).to eq(0) end end context "with goals" do before do @experiment = { "link_color" => ["purchase", "refund"] } @alternatives = ["blue", "red"] @experiment_name, @goals = normalize_metric(@experiment) @goal1 = @goals[0] @goal2 = @goals[1] end it "should normalize experiment" do expect(@experiment_name).to eq("link_color") expect(@goals).to eq(["purchase", "refund"]) end describe "ab_test" do it "should allow experiment goals interface as a single hash" do ab_test(@experiment, *@alternatives) experiment = Split::ExperimentCatalog.find("link_color") expect(experiment.goals).to eq(["purchase", "refund"]) end end describe "ab_finished" do before do @alternative_name = ab_test(@experiment, *@alternatives) end it "should increment the counter for the specified-goal completed alternative" do expect { ab_finished({ "link_color" => ["purchase"] }) } .to change { Split::Alternative.new(@alternative_name, @experiment_name).completed_count(@goal2) }.by(0) .and change { Split::Alternative.new(@alternative_name, @experiment_name).completed_count(@goal1) }.by(1) end end end end <MSG> Merge pull request #53 from leocassarani/issue-52 Fix failing tests on Rubinius (issue #52) <DFF> @@ -319,7 +319,7 @@ describe Split::Helper do context 'when redis is not available' do before(:each) do - Split.stub(:redis).and_raise(Errno::ECONNREFUSED) + Split.stub(:redis).and_raise(Errno::ECONNREFUSED.new) end context 'and db_failover config option is turned off' do
1
Merge pull request #53 from leocassarani/issue-52
1
.rb
rb
mit
splitrb/split
10072060
<NME> helper_spec.rb <BEF> # frozen_string_literal: true require "spec_helper" # TODO change some of these tests to use Rack::Test describe Split::Helper do include Split::Helper let(:experiment) { Split::ExperimentCatalog.find_or_create("link_color", "blue", "red") } describe "ab_test" do it "should not raise an error when passed strings for alternatives" do expect { ab_test("xyz", "1", "2", "3") }.not_to raise_error end it "should not raise an error when passed an array for alternatives" do expect { ab_test("xyz", ["1", "2", "3"]) }.not_to raise_error end it "should raise the appropriate error when passed integers for alternatives" do expect { ab_test("xyz", 1, 2, 3) }.to raise_error(ArgumentError) end it "should raise the appropriate error when passed symbols for alternatives" do expect { ab_test("xyz", :a, :b, :c) }.to raise_error(ArgumentError) end it "should not raise error when passed an array for goals" do expect { ab_test({ "link_color" => ["purchase", "refund"] }, "blue", "red") }.not_to raise_error end it "should not raise error when passed just one goal" do expect { ab_test({ "link_color" => "purchase" }, "blue", "red") }.not_to raise_error end it "raises an appropriate error when processing combined expirements" do Split.configuration.experiments = { combined_exp_1: { alternatives: [ { name: "control", percent: 50 }, { name: "test-alt", percent: 50 } ], metric: :my_metric, combined_experiments: [:combined_exp_1_sub_1] } } Split::ExperimentCatalog.find_or_create("combined_exp_1") expect { ab_test("combined_exp_1") }.to raise_error(Split::InvalidExperimentsFormatError) end it "should assign a random alternative to a new user when there are an equal number of alternatives assigned" do ab_test("link_color", "blue", "red") expect(["red", "blue"]).to include(ab_user["link_color"]) end it "should increment the participation counter after assignment to a new user" do previous_red_count = Split::Alternative.new("red", "link_color").participant_count previous_blue_count = Split::Alternative.new("blue", "link_color").participant_count ab_test("link_color", "blue", "red") new_red_count = Split::Alternative.new("red", "link_color").participant_count new_blue_count = Split::Alternative.new("blue", "link_color").participant_count expect((new_red_count + new_blue_count)).to eq(previous_red_count + previous_blue_count + 1) end it "should not increment the counter for an experiment that the user is not participating in" do ab_test("link_color", "blue", "red") e = Split::ExperimentCatalog.find_or_create("button_size", "small", "big") expect { # User shouldn't participate in this second experiment ab_test("button_size", "small", "big") }.not_to change { e.participant_count } end it "should not increment the counter for an ended experiment" do e = Split::ExperimentCatalog.find_or_create("button_size", "small", "big") e.winner = "small" expect { a = ab_test("button_size", "small", "big") expect(a).to eq("small") }.not_to change { e.participant_count } end it "should not increment the counter for an not started experiment" do expect(Split.configuration).to receive(:start_manually).and_return(true) e = Split::ExperimentCatalog.find_or_create("button_size", "small", "big") expect { a = ab_test("button_size", "small", "big") expect(a).to eq("small") }.not_to change { e.participant_count } end it "should return the given alternative for an existing user" do expect(ab_test("link_color", "blue", "red")).to eq ab_test("link_color", "blue", "red") end it "should always return the winner if one is present" do experiment.winner = "orange" expect(ab_test("link_color", "blue", "red")).to eq("orange") end it "should allow the alternative to be forced by passing it in the params" do # ?ab_test[link_color]=blue @params = { "ab_test" => { "link_color" => "blue" } } alternative = ab_test("link_color", "blue", "red") expect(alternative).to eq("blue") alternative = ab_test("link_color", { "blue" => 1 }, "red" => 5) expect(alternative).to eq("blue") @params = { "ab_test" => { "link_color" => "red" } } alternative = ab_test("link_color", "blue", "red") expect(alternative).to eq("red") alternative = ab_test("link_color", { "blue" => 5 }, "red" => 1) expect(alternative).to eq("red") end it "should not allow an arbitrary alternative" do @params = { "ab_test" => { "link_color" => "pink" } } alternative = ab_test("link_color", "blue") expect(alternative).to eq("blue") end it "should not store the split when a param forced alternative" do @params = { "ab_test" => { "link_color" => "blue" } } expect(ab_user).not_to receive(:[]=) ab_test("link_color", "blue", "red") end it "SPLIT_DISABLE query parameter should also force the alternative (uses control)" do @params = { "SPLIT_DISABLE" => "true" } alternative = ab_test("link_color", "blue", "red") expect(alternative).to eq("blue") alternative = ab_test("link_color", { "blue" => 1 }, "red" => 5) expect(alternative).to eq("blue") alternative = ab_test("link_color", "red", "blue") expect(alternative).to eq("red") alternative = ab_test("link_color", { "red" => 5 }, "blue" => 1) expect(alternative).to eq("red") end it "should not store the split when Split generically disabled" do @params = { "SPLIT_DISABLE" => "true" } expect(ab_user).not_to receive(:[]=) ab_test("link_color", "blue", "red") end context "when store_override is set" do before { Split.configuration.store_override = true } it "should store the forced alternative" do @params = { "ab_test" => { "link_color" => "blue" } } expect(ab_user).to receive(:[]=).with("link_color", "blue") ab_test("link_color", "blue", "red") end end context "when on_trial_choose is set" do before { Split.configuration.on_trial_choose = :some_method } it "should call the method" do expect(self).to receive(:some_method) ab_test("link_color", "blue", "red") end end it "should allow passing a block" do alt = ab_test("link_color", "blue", "red") ret = ab_test("link_color", "blue", "red") { |alternative| "shared/#{alternative}" } expect(ret).to eq("shared/#{alt}") end it "should allow the share of visitors see an alternative to be specified" do ab_test("link_color", { "blue" => 0.8 }, { "red" => 20 }) expect(["red", "blue"]).to include(ab_user["link_color"]) end it "should allow alternative weighting interface as a single hash" do ab_test("link_color", { "blue" => 0.01 }, "red" => 0.2) experiment = Split::ExperimentCatalog.find("link_color") expect(experiment.alternatives.map(&:name)).to eq(["blue", "red"]) expect(experiment.alternatives.collect { |a| a.weight }).to match_array([0.01, 0.2]) end it "should only let a user participate in one experiment at a time" do link_color = ab_test("link_color", "blue", "red") ab_test("button_size", "small", "big") expect(ab_user["link_color"]).to eq(link_color) big = Split::Alternative.new("big", "button_size") expect(big.participant_count).to eq(0) small = Split::Alternative.new("small", "button_size") expect(small.participant_count).to eq(0) end it "should let a user participate in many experiment with allow_multiple_experiments option" do Split.configure do |config| config.allow_multiple_experiments = true end link_color = ab_test("link_color", "blue", "red") button_size = ab_test("button_size", "small", "big") expect(ab_user["link_color"]).to eq(link_color) expect(ab_user["button_size"]).to eq(button_size) button_size_alt = Split::Alternative.new(button_size, "button_size") expect(button_size_alt.participant_count).to eq(1) end context "with allow_multiple_experiments = 'control'" do it "should let a user participate in many experiment with one non-'control' alternative" do Split.configure do |config| config.allow_multiple_experiments = "control" end groups = 100.times.map do |n| ab_test("test#{n}".to_sym, { "control" => (100 - n) }, { "test#{n}-alt" => n }) end experiments = ab_user.active_experiments expect(experiments.size).to be > 1 count_control = experiments.values.count { |g| g == "control" } expect(count_control).to eq(experiments.size - 1) count_alts = groups.count { |g| g != "control" } expect(count_alts).to eq(1) end context "when user already has experiment" do let(:mock_user) { Split::User.new(self, { "test_0" => "test-alt" }) } before do Split.configure do |config| config.allow_multiple_experiments = "control" end Split::ExperimentCatalog.find_or_initialize("test_0", "control", "test-alt").save Split::ExperimentCatalog.find_or_initialize("test_1", "control", "test-alt").save end it "should restore previously selected alternative" do expect(ab_user.active_experiments.size).to eq 1 expect(ab_test(:test_0, { "control" => 100 }, { "test-alt" => 1 })).to eq "test-alt" expect(ab_test(:test_0, { "control" => 1 }, { "test-alt" => 100 })).to eq "test-alt" end it "should select the correct alternatives after experiment resets" do experiment = Split::ExperimentCatalog.find(:test_0) experiment.reset mock_user[experiment.key] = "test-alt" expect(ab_user.active_experiments.size).to eq 1 expect(ab_test(:test_0, { "control" => 100 }, { "test-alt" => 1 })).to eq "test-alt" expect(ab_test(:test_0, { "control" => 0 }, { "test-alt" => 100 })).to eq "test-alt" end it "lets override existing choice" do pending "this requires user store reset on first call not depending on whelther it is current trial" @params = { "ab_test" => { "test_1" => "test-alt" } } expect(ab_test(:test_0, { "control" => 0 }, { "test-alt" => 100 })).to eq "control" expect(ab_test(:test_1, { "control" => 100 }, { "test-alt" => 1 })).to eq "test-alt" end end end it "should not over-write a finished key when an experiment is on a later version" do experiment.increment_version ab_user = { experiment.key => "blue", experiment.finished_key => true } finished_session = ab_user.dup ab_test("link_color", "blue", "red") expect(ab_user).to eq(finished_session) end end describe "metadata" do context "is defined" do before do Split.configuration.experiments = { my_experiment: { alternatives: ["one", "two"], resettable: false, metadata: { "one" => "Meta1", "two" => "Meta2" } } } end it "should be passed to helper block" do @params = { "ab_test" => { "my_experiment" => "two" } } expect(ab_test("my_experiment")).to eq "two" expect(ab_test("my_experiment") do |alternative, meta| meta end).to eq("Meta2") end it "should pass control metadata helper block if library disabled" do Split.configure do |config| config.enabled = false end expect(ab_test("my_experiment")).to eq "one" expect(ab_test("my_experiment") do |_, meta| meta end).to eq("Meta1") end end context "is not defined" do before do Split.configuration.experiments = { my_experiment: { alternatives: ["one", "two"], resettable: false, metadata: nil } } context 'when redis is not available' do before(:each) do Split.stub(:redis).and_raise(Errno::ECONNREFUSED) end context 'and db_failover config option is turned off' do it "should pass control metadata helper block if library disabled" do Split.configure do |config| config.enabled = false end expect(ab_test("my_experiment") do |_, meta| meta end).to eq({}) end end end describe "ab_finished" do context "for an experiment that the user participates in" do before(:each) do @experiment_name = "link_color" @alternatives = ["blue", "red"] @experiment = Split::ExperimentCatalog.find_or_create(@experiment_name, *@alternatives) @alternative_name = ab_test(@experiment_name, *@alternatives) @previous_completion_count = Split::Alternative.new(@alternative_name, @experiment_name).completed_count end it "should increment the counter for the completed alternative" do ab_finished(@experiment_name) new_completion_count = Split::Alternative.new(@alternative_name, @experiment_name).completed_count expect(new_completion_count).to eq(@previous_completion_count + 1) end it "should set experiment's finished key if reset is false" do ab_finished(@experiment_name, { reset: false }) expect(ab_user[@experiment.key]).to eq(@alternative_name) expect(ab_user[@experiment.finished_key]).to eq(true) end it "should not increment the counter if reset is false and the experiment has been already finished" do 2.times { ab_finished(@experiment_name, { reset: false }) } new_completion_count = Split::Alternative.new(@alternative_name, @experiment_name).completed_count expect(new_completion_count).to eq(@previous_completion_count + 1) end it "should not increment the counter for an ended experiment" do e = Split::ExperimentCatalog.find_or_create("button_size", "small", "big") e.winner = "small" a = ab_test("button_size", "small", "big") expect(a).to eq("small") expect { ab_finished("button_size") }.not_to change { Split::Alternative.new(a, "button_size").completed_count } end it "should clear out the user's participation from their session" do expect(ab_user[@experiment.key]).to eq(@alternative_name) ab_finished(@experiment_name) expect(ab_user.keys).to be_empty end it "should not clear out the users session if reset is false" do expect(ab_user[@experiment.key]).to eq(@alternative_name) ab_finished(@experiment_name, { reset: false }) expect(ab_user[@experiment.key]).to eq(@alternative_name) expect(ab_user[@experiment.finished_key]).to eq(true) end it "should reset the users session when experiment is not versioned" do expect(ab_user[@experiment.key]).to eq(@alternative_name) ab_finished(@experiment_name) expect(ab_user.keys).to be_empty end it "should reset the users session when experiment is versioned" do @experiment.increment_version @alternative_name = ab_test(@experiment_name, *@alternatives) expect(ab_user[@experiment.key]).to eq(@alternative_name) ab_finished(@experiment_name) expect(ab_user.keys).to be_empty end context "when on_trial_complete is set" do before { Split.configuration.on_trial_complete = :some_method } it "should call the method" do expect(self).to receive(:some_method) ab_finished(@experiment_name) end it "should not call the method without alternative" do ab_user[@experiment.key] = nil expect(self).not_to receive(:some_method) ab_finished(@experiment_name) end end end context "for an experiment that the user is excluded from" do before do alternative = ab_test("link_color", "blue", "red") expect(Split::Alternative.new(alternative, "link_color").participant_count).to eq(1) alternative = ab_test("button_size", "small", "big") expect(Split::Alternative.new(alternative, "button_size").participant_count).to eq(0) end it "should not increment the completed counter" do # So, user should be participating in the link_color experiment and # receive the control for button_size. As the user is not participating in # the button size experiment, finishing it should not increase the # completion count for that alternative. expect { ab_finished("button_size") }.not_to change { Split::Alternative.new("small", "button_size").completed_count } end end context "for an experiment that the user does not participate in" do before do Split::ExperimentCatalog.find_or_create(:not_started_experiment, "control", "alt") end it "should not raise an exception" do expect { ab_finished(:not_started_experiment) }.not_to raise_exception end it "should not change the user state when reset is false" do expect { ab_finished(:not_started_experiment, reset: false) }.not_to change { ab_user.keys }.from([]) end it "should not change the user state when reset is true" do expect(self).not_to receive(:reset!) ab_finished(:not_started_experiment) end it "should not increment the completed counter" do ab_finished(:not_started_experiment) expect(Split::Alternative.new("control", :not_started_experiment).completed_count).to eq(0) expect(Split::Alternative.new("alt", :not_started_experiment).completed_count).to eq(0) end end end context "finished with config" do it "passes reset option" do Split.configuration.experiments = { my_experiment: { alternatives: ["one", "two"], resettable: false, } } alternative = ab_test(:my_experiment) experiment = Split::ExperimentCatalog.find :my_experiment ab_finished :my_experiment expect(ab_user[experiment.key]).to eq(alternative) expect(ab_user[experiment.finished_key]).to eq(true) end end context "finished with metric name" do before { Split.configuration.experiments = {} } before { expect(Split::Alternative).to receive(:new).at_least(1).times.and_call_original } def should_finish_experiment(experiment_name, should_finish = true) alts = Split.configuration.experiments[experiment_name][:alternatives] experiment = Split::ExperimentCatalog.find_or_create(experiment_name, *alts) alt_name = ab_user[experiment.key] = alts.first alt = double("alternative") expect(alt).to receive(:name).at_most(1).times.and_return(alt_name) expect(Split::Alternative).to receive(:new).at_most(1).times.with(alt_name, experiment_name.to_s).and_return(alt) if should_finish expect(alt).to receive(:increment_completion).at_most(1).times else expect(alt).not_to receive(:increment_completion) end end it "completes the test" do Split.configuration.experiments[:my_experiment] = { alternatives: [ "control_opt", "other_opt" ], metric: :my_metric } should_finish_experiment :my_experiment ab_finished :my_metric end it "completes all relevant tests" do Split.configuration.experiments = { exp_1: { alternatives: [ "1-1", "1-2" ], metric: :my_metric }, exp_2: { alternatives: [ "2-1", "2-2" ], metric: :another_metric }, exp_3: { alternatives: [ "3-1", "3-2" ], metric: :my_metric }, } should_finish_experiment :exp_1 should_finish_experiment :exp_2, false should_finish_experiment :exp_3 ab_finished :my_metric end it "passes reset option" do Split.configuration.experiments = { my_exp: { alternatives: ["one", "two"], metric: :my_metric, resettable: false, } } alternative_name = ab_test(:my_exp) exp = Split::ExperimentCatalog.find :my_exp ab_finished :my_metric expect(ab_user[exp.key]).to eq(alternative_name) expect(ab_user[exp.finished_key]).to be_truthy end it "passes through options" do Split.configuration.experiments = { my_exp: { alternatives: ["one", "two"], metric: :my_metric, } } alternative_name = ab_test(:my_exp) exp = Split::ExperimentCatalog.find :my_exp ab_finished :my_metric, reset: false expect(ab_user[exp.key]).to eq(alternative_name) expect(ab_user[exp.finished_key]).to be_truthy end end describe "conversions" do it "should return a conversion rate for an alternative" do alternative_name = ab_test("link_color", "blue", "red") previous_convertion_rate = Split::Alternative.new(alternative_name, "link_color").conversion_rate expect(previous_convertion_rate).to eq(0.0) ab_finished("link_color") new_convertion_rate = Split::Alternative.new(alternative_name, "link_color").conversion_rate expect(new_convertion_rate).to eq(1.0) end end describe "active experiments" do it "should show an active test" do alternative = ab_test("def", "4", "5", "6") expect(active_experiments.count).to eq 1 expect(active_experiments.first[0]).to eq "def" expect(active_experiments.first[1]).to eq alternative end it "should show a finished test" do alternative = ab_test("def", "4", "5", "6") ab_finished("def", { reset: false }) expect(active_experiments.count).to eq 1 expect(active_experiments.first[0]).to eq "def" expect(active_experiments.first[1]).to eq alternative end it "should show an active test when an experiment is on a later version" do experiment.reset expect(experiment.version).to eq(1) ab_test("link_color", "blue", "red") expect(active_experiments.count).to eq 1 expect(active_experiments.first[0]).to eq "link_color" end it "should show versioned tests properly" do 10.times { experiment.reset } alternative = ab_test(experiment.name, "blue", "red") ab_finished(experiment.name, reset: false) expect(experiment.version).to eq(10) expect(active_experiments.count).to eq 1 expect(active_experiments).to eq({ "link_color" => alternative }) end it "should show multiple tests" do Split.configure do |config| config.allow_multiple_experiments = true end alternative = ab_test("def", "4", "5", "6") another_alternative = ab_test("ghi", "7", "8", "9") expect(active_experiments.count).to eq 2 expect(active_experiments["def"]).to eq alternative expect(active_experiments["ghi"]).to eq another_alternative end it "should not show tests with winners" do Split.configure do |config| config.allow_multiple_experiments = true end e = Split::ExperimentCatalog.find_or_create("def", "4", "5", "6") e.winner = "4" ab_test("def", "4", "5", "6") another_alternative = ab_test("ghi", "7", "8", "9") expect(active_experiments.count).to eq 1 expect(active_experiments.first[0]).to eq "ghi" expect(active_experiments.first[1]).to eq another_alternative end end describe "when user is a robot" do before(:each) do @request = OpenStruct.new(user_agent: "Googlebot/2.1 (+http://www.google.com/bot.html)") end describe "ab_test" do it "should return the control" do alternative = ab_test("link_color", "blue", "red") expect(alternative).to eq experiment.control.name end it "should not create a experiment" do ab_test("link_color", "blue", "red") expect(Split::Experiment.new("link_color")).to be_a_new_record end it "should not increment the participation count" do previous_red_count = Split::Alternative.new("red", "link_color").participant_count previous_blue_count = Split::Alternative.new("blue", "link_color").participant_count ab_test("link_color", "blue", "red") new_red_count = Split::Alternative.new("red", "link_color").participant_count new_blue_count = Split::Alternative.new("blue", "link_color").participant_count expect((new_red_count + new_blue_count)).to eq(previous_red_count + previous_blue_count) end end describe "finished" do it "should not increment the completed count" do alternative_name = ab_test("link_color", "blue", "red") previous_completion_count = Split::Alternative.new(alternative_name, "link_color").completed_count ab_finished("link_color") new_completion_count = Split::Alternative.new(alternative_name, "link_color").completed_count expect(new_completion_count).to eq(previous_completion_count) end end end describe "when providing custom ignore logic" do context "using a proc to configure custom logic" do before(:each) do Split.configure do |c| c.ignore_filter = proc { |request| true } # ignore everything end end it "ignores the ab_test" do ab_test("link_color", "blue", "red") red_count = Split::Alternative.new("red", "link_color").participant_count blue_count = Split::Alternative.new("blue", "link_color").participant_count expect((red_count + blue_count)).to be(0) end end end shared_examples_for "a disabled test" do describe "ab_test" do it "should return the control" do alternative = ab_test("link_color", "blue", "red") expect(alternative).to eq experiment.control.name end it "should not increment the participation count" do previous_red_count = Split::Alternative.new("red", "link_color").participant_count previous_blue_count = Split::Alternative.new("blue", "link_color").participant_count ab_test("link_color", "blue", "red") new_red_count = Split::Alternative.new("red", "link_color").participant_count new_blue_count = Split::Alternative.new("blue", "link_color").participant_count expect((new_red_count + new_blue_count)).to eq(previous_red_count + previous_blue_count) end end describe "finished" do it "should not increment the completed count" do alternative_name = ab_test("link_color", "blue", "red") previous_completion_count = Split::Alternative.new(alternative_name, "link_color").completed_count ab_finished("link_color") new_completion_count = Split::Alternative.new(alternative_name, "link_color").completed_count expect(new_completion_count).to eq(previous_completion_count) end end end describe "when ip address is ignored" do context "individually" do before(:each) do @request = OpenStruct.new(ip: "81.19.48.130") Split.configure do |c| c.ignore_ip_addresses << "81.19.48.130" end end it_behaves_like "a disabled test" end context "for a range" do before(:each) do @request = OpenStruct.new(ip: "81.19.48.129") Split.configure do |c| c.ignore_ip_addresses << /81\.19\.48\.[0-9]+/ end end it_behaves_like "a disabled test" end context "using both a range and a specific value" do before(:each) do @request = OpenStruct.new(ip: "81.19.48.128") Split.configure do |c| c.ignore_ip_addresses << "81.19.48.130" c.ignore_ip_addresses << /81\.19\.48\.[0-9]+/ end end it_behaves_like "a disabled test" end context "when ignored other address" do before do @request = OpenStruct.new(ip: "1.1.1.1") Split.configure do |c| c.ignore_ip_addresses << "81.19.48.130" end end it "works as usual" do alternative_name = ab_test("link_color", "red", "blue") expect { ab_finished("link_color") }.to change(Split::Alternative.new(alternative_name, "link_color"), :completed_count).by(1) end end end describe "when user is previewing" do before(:each) do @request = OpenStruct.new(headers: { "x-purpose" => "preview" }) end it_behaves_like "a disabled test" end describe "versioned experiments" do it "should use version zero if no version is present" do alternative_name = ab_test("link_color", "blue", "red") expect(experiment.version).to eq(0) expect(ab_user["link_color"]).to eq(alternative_name) end it "should save the version of the experiment to the session" do experiment.reset expect(experiment.version).to eq(1) alternative_name = ab_test("link_color", "blue", "red") expect(ab_user["link_color:1"]).to eq(alternative_name) end it "should load the experiment even if the version is not 0" do experiment.reset expect(experiment.version).to eq(1) alternative_name = ab_test("link_color", "blue", "red") expect(ab_user["link_color:1"]).to eq(alternative_name) return_alternative_name = ab_test("link_color", "blue", "red") expect(return_alternative_name).to eq(alternative_name) end it "should reset the session of a user on an older version of the experiment" do alternative_name = ab_test("link_color", "blue", "red") expect(ab_user["link_color"]).to eq(alternative_name) alternative = Split::Alternative.new(alternative_name, "link_color") expect(alternative.participant_count).to eq(1) experiment.reset expect(experiment.version).to eq(1) alternative = Split::Alternative.new(alternative_name, "link_color") expect(alternative.participant_count).to eq(0) new_alternative_name = ab_test("link_color", "blue", "red") expect(ab_user["link_color:1"]).to eq(new_alternative_name) new_alternative = Split::Alternative.new(new_alternative_name, "link_color") expect(new_alternative.participant_count).to eq(1) end it "should cleanup old versions of experiments from the session" do alternative_name = ab_test("link_color", "blue", "red") expect(ab_user["link_color"]).to eq(alternative_name) alternative = Split::Alternative.new(alternative_name, "link_color") expect(alternative.participant_count).to eq(1) experiment.reset expect(experiment.version).to eq(1) alternative = Split::Alternative.new(alternative_name, "link_color") expect(alternative.participant_count).to eq(0) new_alternative_name = ab_test("link_color", "blue", "red") expect(ab_user["link_color:1"]).to eq(new_alternative_name) end it "should only count completion of users on the current version" do alternative_name = ab_test("link_color", "blue", "red") expect(ab_user["link_color"]).to eq(alternative_name) Split::Alternative.new(alternative_name, "link_color") experiment.reset expect(experiment.version).to eq(1) ab_finished("link_color") alternative = Split::Alternative.new(alternative_name, "link_color") expect(alternative.completed_count).to eq(0) end end context "when redis is not available" do before(:each) do expect(Split).to receive(:redis).at_most(5).times.and_raise(Errno::ECONNREFUSED.new) end context "and db_failover config option is turned off" do before(:each) do Split.configure do |config| config.db_failover = false end end describe "ab_test" do it "should raise an exception" do expect { ab_test("link_color", "blue", "red") }.to raise_error(Errno::ECONNREFUSED) end end describe "finished" do it "should raise an exception" do expect { ab_finished("link_color") }.to raise_error(Errno::ECONNREFUSED) end end describe "disable split testing" do before(:each) do Split.configure do |config| config.enabled = false end end it "should not attempt to connect to redis" do expect { ab_test("link_color", "blue", "red") }.not_to raise_error end it "should return control variable" do expect(ab_test("link_color", "blue", "red")).to eq("blue") expect { ab_finished("link_color") }.not_to raise_error end end end context "and db_failover config option is turned on" do before(:each) do Split.configure do |config| config.db_failover = true end end describe "ab_test" do it "should not raise an exception" do expect { ab_test("link_color", "blue", "red") }.not_to raise_error end it "should call db_failover_on_db_error proc with error as parameter" do Split.configure do |config| config.db_failover_on_db_error = proc do |error| expect(error).to be_a(Errno::ECONNREFUSED) end end expect(Split.configuration.db_failover_on_db_error).to receive(:call).and_call_original ab_test("link_color", "blue", "red") end it "should always use first alternative" do expect(ab_test("link_color", "blue", "red")).to eq("blue") expect(ab_test("link_color", { "blue" => 0.01 }, "red" => 0.2)).to eq("blue") expect(ab_test("link_color", { "blue" => 0.8 }, { "red" => 20 })).to eq("blue") expect(ab_test("link_color", "blue", "red") do |alternative| "shared/#{alternative}" end).to eq("shared/blue") end context "and db_failover_allow_parameter_override config option is turned on" do before(:each) do Split.configure do |config| config.db_failover_allow_parameter_override = true end end context "and given an override parameter" do it "should use given override instead of the first alternative" do @params = { "ab_test" => { "link_color" => "red" } } expect(ab_test("link_color", "blue", "red")).to eq("red") expect(ab_test("link_color", "blue", "red", "green")).to eq("red") expect(ab_test("link_color", { "blue" => 0.01 }, "red" => 0.2)).to eq("red") expect(ab_test("link_color", { "blue" => 0.8 }, { "red" => 20 })).to eq("red") expect(ab_test("link_color", "blue", "red") do |alternative| "shared/#{alternative}" end).to eq("shared/red") end end end context "and preloaded config given" do before do Split.configuration.experiments[:link_color] = { alternatives: [ "blue", "red" ], } end it "uses first alternative" do expect(ab_test(:link_color)).to eq("blue") end end end describe "finished" do it "should not raise an exception" do expect { ab_finished("link_color") }.not_to raise_error end it "should call db_failover_on_db_error proc with error as parameter" do Split.configure do |config| config.db_failover_on_db_error = proc do |error| expect(error).to be_a(Errno::ECONNREFUSED) end end expect(Split.configuration.db_failover_on_db_error).to receive(:call).and_call_original ab_finished("link_color") end end end end context "with preloaded config" do before { Split.configuration.experiments = {} } it "pulls options from config file" do Split.configuration.experiments[:my_experiment] = { alternatives: [ "control_opt", "other_opt" ], goals: ["goal1", "goal2"] } ab_test :my_experiment expect(Split::Experiment.new(:my_experiment).alternatives.map(&:name)).to eq([ "control_opt", "other_opt" ]) expect(Split::Experiment.new(:my_experiment).goals).to eq([ "goal1", "goal2" ]) end it "can be called multiple times" do Split.configuration.experiments[:my_experiment] = { alternatives: [ "control_opt", "other_opt" ], goals: ["goal1", "goal2"] } 5.times { ab_test :my_experiment } experiment = Split::Experiment.new(:my_experiment) expect(experiment.alternatives.map(&:name)).to eq([ "control_opt", "other_opt" ]) expect(experiment.goals).to eq([ "goal1", "goal2" ]) expect(experiment.participant_count).to eq(1) end it "accepts multiple goals" do Split.configuration.experiments[:my_experiment] = { alternatives: [ "control_opt", "other_opt" ], goals: [ "goal1", "goal2", "goal3" ] } ab_test :my_experiment experiment = Split::Experiment.new(:my_experiment) expect(experiment.goals).to eq([ "goal1", "goal2", "goal3" ]) end it "allow specifying goals to be optional" do Split.configuration.experiments[:my_experiment] = { alternatives: [ "control_opt", "other_opt" ] } experiment = Split::Experiment.new(:my_experiment) expect(experiment.goals).to eq([]) end it "accepts multiple alternatives" do Split.configuration.experiments[:my_experiment] = { alternatives: [ "control_opt", "second_opt", "third_opt" ], } ab_test :my_experiment experiment = Split::Experiment.new(:my_experiment) expect(experiment.alternatives.map(&:name)).to eq([ "control_opt", "second_opt", "third_opt" ]) end it "accepts probability on alternatives" do Split.configuration.experiments[:my_experiment] = { alternatives: [ { name: "control_opt", percent: 67 }, { name: "second_opt", percent: 10 }, { name: "third_opt", percent: 23 }, ], } ab_test :my_experiment experiment = Split::Experiment.new(:my_experiment) expect(experiment.alternatives.collect { |a| [a.name, a.weight] }).to eq([["control_opt", 0.67], ["second_opt", 0.1], ["third_opt", 0.23]]) end it "accepts probability on some alternatives" do Split.configuration.experiments[:my_experiment] = { alternatives: [ { name: "control_opt", percent: 34 }, "second_opt", { name: "third_opt", percent: 23 }, "fourth_opt", ], } ab_test :my_experiment experiment = Split::Experiment.new(:my_experiment) names_and_weights = experiment.alternatives.collect { |a| [a.name, a.weight] } expect(names_and_weights).to eq([["control_opt", 0.34], ["second_opt", 0.215], ["third_opt", 0.23], ["fourth_opt", 0.215]]) expect(names_and_weights.inject(0) { |sum, nw| sum + nw[1] }).to eq(1.0) end it "allows name param without probability" do Split.configuration.experiments[:my_experiment] = { alternatives: [ { name: "control_opt" }, "second_opt", { name: "third_opt", percent: 64 }, ], } ab_test :my_experiment experiment = Split::Experiment.new(:my_experiment) names_and_weights = experiment.alternatives.collect { |a| [a.name, a.weight] } expect(names_and_weights).to eq([["control_opt", 0.18], ["second_opt", 0.18], ["third_opt", 0.64]]) expect(names_and_weights.inject(0) { |sum, nw| sum + nw[1] }).to eq(1.0) end it "fails gracefully if config is missing experiment" do Split.configuration.experiments = { other_experiment: { foo: "Bar" } } expect { ab_test :my_experiment }.to raise_error(Split::ExperimentNotFound) end it "fails gracefully if config is missing" do expect { Split.configuration.experiments = nil }.to raise_error(Split::InvalidExperimentsFormatError) end it "fails gracefully if config is missing alternatives" do Split.configuration.experiments[:my_experiment] = { foo: "Bar" } expect { ab_test :my_experiment }.to raise_error(NoMethodError) end end it "should handle multiple experiments correctly" do experiment2 = Split::ExperimentCatalog.find_or_create("link_color2", "blue", "red") ab_test("link_color", "blue", "red") ab_test("link_color2", "blue", "red") ab_finished("link_color2") experiment2.alternatives.each do |alt| expect(alt.unfinished_count).to eq(0) end end context "with goals" do before do @experiment = { "link_color" => ["purchase", "refund"] } @alternatives = ["blue", "red"] @experiment_name, @goals = normalize_metric(@experiment) @goal1 = @goals[0] @goal2 = @goals[1] end it "should normalize experiment" do expect(@experiment_name).to eq("link_color") expect(@goals).to eq(["purchase", "refund"]) end describe "ab_test" do it "should allow experiment goals interface as a single hash" do ab_test(@experiment, *@alternatives) experiment = Split::ExperimentCatalog.find("link_color") expect(experiment.goals).to eq(["purchase", "refund"]) end end describe "ab_finished" do before do @alternative_name = ab_test(@experiment, *@alternatives) end it "should increment the counter for the specified-goal completed alternative" do expect { ab_finished({ "link_color" => ["purchase"] }) } .to change { Split::Alternative.new(@alternative_name, @experiment_name).completed_count(@goal2) }.by(0) .and change { Split::Alternative.new(@alternative_name, @experiment_name).completed_count(@goal1) }.by(1) end end end end <MSG> Merge pull request #53 from leocassarani/issue-52 Fix failing tests on Rubinius (issue #52) <DFF> @@ -319,7 +319,7 @@ describe Split::Helper do context 'when redis is not available' do before(:each) do - Split.stub(:redis).and_raise(Errno::ECONNREFUSED) + Split.stub(:redis).and_raise(Errno::ECONNREFUSED.new) end context 'and db_failover config option is turned off' do
1
Merge pull request #53 from leocassarani/issue-52
1
.rb
rb
mit
splitrb/split
10072061
<NME> cookie_adapter_spec.rb <BEF> # frozen_string_literal: true require "spec_helper" require "rack/test" describe Split::Persistence::CookieAdapter do subject { described_class.new(context) } shared_examples "sets cookies correctly" do describe "#[] and #[]=" do it "set and return the value for given key" do subject["my_key"] = "my_value" expect(subject["my_key"]).to eq("my_value") end it "handles invalid JSON" do context.request.cookies[:split] = { value: '{"foo":2,', expires: Time.now } expect(subject["my_key"]).to be_nil subject["my_key"] = "my_value" expect(subject["my_key"]).to eq("my_value") end it "ignores valid JSON of invalid type (integer)" do context.request.cookies["split"] = "2" expect(subject["my_key"]).to be_nil subject["my_key"] = "my_value" expect(subject["my_key"]).to eq("my_value") end it "ignores valid JSON of invalid type (array)" do context.request.cookies["split"] = "[\"foo\", \"bar\"]" expect(subject["my_key"]).to be_nil 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 session'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 context "when using Rack" do let(:env) { Rack::MockRequest.env_for("http://example.com:8080/") } let(:request) { Rack::Request.new(env) } let(:response) { Rack::MockResponse.new(200, {}, "") } let(:context) { double(request: request, response: response, cookies: CookiesMock.new) } include_examples "sets cookies correctly" it "puts multiple experiments in a single cookie" do subject["foo"] = "FOO" subject["bar"] = "BAR" expect(context.response.headers["Set-Cookie"]).to match(/\Asplit=%7B%22foo%22%3A%22FOO%22%2C%22bar%22%3A%22BAR%22%7D; path=\/; expires=[a-zA-Z]{3}, \d{2} [a-zA-Z]{3} \d{4} \d{2}:\d{2}:\d{2} [A-Z]{3}\Z/) end it "ensure other added cookies are not overriden" do context.response.set_cookie "dummy", "wow" subject["foo"] = "FOO" expect(context.response.headers["Set-Cookie"]).to include("dummy=wow") expect(context.response.headers["Set-Cookie"]).to include("split=") end end context "when @context is an ActionController::Base" do before :context do require "rails" require "action_controller/railtie" end let(:context) do controller = controller_class.new if controller.respond_to?(:set_request!) controller.set_request!(ActionDispatch::Request.new({})) else # Before rails 5.0 controller.send(:"request=", ActionDispatch::Request.new({})) end response = ActionDispatch::Response.new(200, {}, "").tap do |res| res.request = controller.request end if controller.respond_to?(:set_response!) controller.set_response!(response) else # Before rails 5.0 controller.send(:set_response!, response) end controller end let(:controller_class) { Class.new(ActionController::Base) } include_examples "sets cookies correctly" it "puts multiple experiments in a single cookie" do subject["foo"] = "FOO" subject["bar"] = "BAR" expect(subject.keys).to eq(["foo", "bar"]) expect(subject["foo"]).to eq("FOO") expect(subject["bar"]).to eq("BAR") cookie_jar = context.request.env["action_dispatch.cookies"] expect(cookie_jar["split"]).to eq('{"foo":"FOO","bar":"BAR"}') end end end <MSG> Fix spec for parsing invalid JSON The cookie adapter uses string as a key, so should the spec. Also, context.request.cookies is a hash in both cases, it feels that it should be set directly, not using a hash with "value" and "expires" keys. <DFF> @@ -14,10 +14,8 @@ describe Split::Persistence::CookieAdapter do end it "handles invalid JSON" do - context.request.cookies[:split] = { - value: '{"foo":2,', - expires: Time.now - } + context.request.cookies["split"] = "{\"foo\":2," + expect(subject["my_key"]).to be_nil subject["my_key"] = "my_value" expect(subject["my_key"]).to eq("my_value")
2
Fix spec for parsing invalid JSON
4
.rb
rb
mit
splitrb/split
10072062
<NME> cookie_adapter_spec.rb <BEF> # frozen_string_literal: true require "spec_helper" require "rack/test" describe Split::Persistence::CookieAdapter do subject { described_class.new(context) } shared_examples "sets cookies correctly" do describe "#[] and #[]=" do it "set and return the value for given key" do subject["my_key"] = "my_value" expect(subject["my_key"]).to eq("my_value") end it "handles invalid JSON" do context.request.cookies[:split] = { value: '{"foo":2,', expires: Time.now } expect(subject["my_key"]).to be_nil subject["my_key"] = "my_value" expect(subject["my_key"]).to eq("my_value") end it "ignores valid JSON of invalid type (integer)" do context.request.cookies["split"] = "2" expect(subject["my_key"]).to be_nil subject["my_key"] = "my_value" expect(subject["my_key"]).to eq("my_value") end it "ignores valid JSON of invalid type (array)" do context.request.cookies["split"] = "[\"foo\", \"bar\"]" expect(subject["my_key"]).to be_nil 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 session'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 context "when using Rack" do let(:env) { Rack::MockRequest.env_for("http://example.com:8080/") } let(:request) { Rack::Request.new(env) } let(:response) { Rack::MockResponse.new(200, {}, "") } let(:context) { double(request: request, response: response, cookies: CookiesMock.new) } include_examples "sets cookies correctly" it "puts multiple experiments in a single cookie" do subject["foo"] = "FOO" subject["bar"] = "BAR" expect(context.response.headers["Set-Cookie"]).to match(/\Asplit=%7B%22foo%22%3A%22FOO%22%2C%22bar%22%3A%22BAR%22%7D; path=\/; expires=[a-zA-Z]{3}, \d{2} [a-zA-Z]{3} \d{4} \d{2}:\d{2}:\d{2} [A-Z]{3}\Z/) end it "ensure other added cookies are not overriden" do context.response.set_cookie "dummy", "wow" subject["foo"] = "FOO" expect(context.response.headers["Set-Cookie"]).to include("dummy=wow") expect(context.response.headers["Set-Cookie"]).to include("split=") end end context "when @context is an ActionController::Base" do before :context do require "rails" require "action_controller/railtie" end let(:context) do controller = controller_class.new if controller.respond_to?(:set_request!) controller.set_request!(ActionDispatch::Request.new({})) else # Before rails 5.0 controller.send(:"request=", ActionDispatch::Request.new({})) end response = ActionDispatch::Response.new(200, {}, "").tap do |res| res.request = controller.request end if controller.respond_to?(:set_response!) controller.set_response!(response) else # Before rails 5.0 controller.send(:set_response!, response) end controller end let(:controller_class) { Class.new(ActionController::Base) } include_examples "sets cookies correctly" it "puts multiple experiments in a single cookie" do subject["foo"] = "FOO" subject["bar"] = "BAR" expect(subject.keys).to eq(["foo", "bar"]) expect(subject["foo"]).to eq("FOO") expect(subject["bar"]).to eq("BAR") cookie_jar = context.request.env["action_dispatch.cookies"] expect(cookie_jar["split"]).to eq('{"foo":"FOO","bar":"BAR"}') end end end <MSG> Fix spec for parsing invalid JSON The cookie adapter uses string as a key, so should the spec. Also, context.request.cookies is a hash in both cases, it feels that it should be set directly, not using a hash with "value" and "expires" keys. <DFF> @@ -14,10 +14,8 @@ describe Split::Persistence::CookieAdapter do end it "handles invalid JSON" do - context.request.cookies[:split] = { - value: '{"foo":2,', - expires: Time.now - } + context.request.cookies["split"] = "{\"foo\":2," + expect(subject["my_key"]).to be_nil subject["my_key"] = "my_value" expect(subject["my_key"]).to eq("my_value")
2
Fix spec for parsing invalid JSON
4
.rb
rb
mit
splitrb/split
10072063
<NME> cookie_adapter_spec.rb <BEF> # frozen_string_literal: true require "spec_helper" require "rack/test" describe Split::Persistence::CookieAdapter do subject { described_class.new(context) } shared_examples "sets cookies correctly" do describe "#[] and #[]=" do it "set and return the value for given key" do subject["my_key"] = "my_value" expect(subject["my_key"]).to eq("my_value") end it "handles invalid JSON" do context.request.cookies[:split] = { value: '{"foo":2,', expires: Time.now } expect(subject["my_key"]).to be_nil subject["my_key"] = "my_value" expect(subject["my_key"]).to eq("my_value") end it "ignores valid JSON of invalid type (integer)" do context.request.cookies["split"] = "2" expect(subject["my_key"]).to be_nil subject["my_key"] = "my_value" expect(subject["my_key"]).to eq("my_value") end it "ignores valid JSON of invalid type (array)" do context.request.cookies["split"] = "[\"foo\", \"bar\"]" expect(subject["my_key"]).to be_nil 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 session'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 context "when using Rack" do let(:env) { Rack::MockRequest.env_for("http://example.com:8080/") } let(:request) { Rack::Request.new(env) } let(:response) { Rack::MockResponse.new(200, {}, "") } let(:context) { double(request: request, response: response, cookies: CookiesMock.new) } include_examples "sets cookies correctly" it "puts multiple experiments in a single cookie" do subject["foo"] = "FOO" subject["bar"] = "BAR" expect(context.response.headers["Set-Cookie"]).to match(/\Asplit=%7B%22foo%22%3A%22FOO%22%2C%22bar%22%3A%22BAR%22%7D; path=\/; expires=[a-zA-Z]{3}, \d{2} [a-zA-Z]{3} \d{4} \d{2}:\d{2}:\d{2} [A-Z]{3}\Z/) end it "ensure other added cookies are not overriden" do context.response.set_cookie "dummy", "wow" subject["foo"] = "FOO" expect(context.response.headers["Set-Cookie"]).to include("dummy=wow") expect(context.response.headers["Set-Cookie"]).to include("split=") end end context "when @context is an ActionController::Base" do before :context do require "rails" require "action_controller/railtie" end let(:context) do controller = controller_class.new if controller.respond_to?(:set_request!) controller.set_request!(ActionDispatch::Request.new({})) else # Before rails 5.0 controller.send(:"request=", ActionDispatch::Request.new({})) end response = ActionDispatch::Response.new(200, {}, "").tap do |res| res.request = controller.request end if controller.respond_to?(:set_response!) controller.set_response!(response) else # Before rails 5.0 controller.send(:set_response!, response) end controller end let(:controller_class) { Class.new(ActionController::Base) } include_examples "sets cookies correctly" it "puts multiple experiments in a single cookie" do subject["foo"] = "FOO" subject["bar"] = "BAR" expect(subject.keys).to eq(["foo", "bar"]) expect(subject["foo"]).to eq("FOO") expect(subject["bar"]).to eq("BAR") cookie_jar = context.request.env["action_dispatch.cookies"] expect(cookie_jar["split"]).to eq('{"foo":"FOO","bar":"BAR"}') end end end <MSG> Fix spec for parsing invalid JSON The cookie adapter uses string as a key, so should the spec. Also, context.request.cookies is a hash in both cases, it feels that it should be set directly, not using a hash with "value" and "expires" keys. <DFF> @@ -14,10 +14,8 @@ describe Split::Persistence::CookieAdapter do end it "handles invalid JSON" do - context.request.cookies[:split] = { - value: '{"foo":2,', - expires: Time.now - } + context.request.cookies["split"] = "{\"foo\":2," + expect(subject["my_key"]).to be_nil subject["my_key"] = "my_value" expect(subject["my_key"]).to eq("my_value")
2
Fix spec for parsing invalid JSON
4
.rb
rb
mit
splitrb/split
10072064
<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.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.add_dependency 'redis', '>= 2.1' s.add_dependency 'sinatra', '>= 1.2.6' s.add_dependency 'simple-random', '>= 0.9.3' s.add_development_dependency 'bundler', '>= 1.17' s.add_development_dependency 'simplecov', '~> 0.15' 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> Replace usage of SimpleRandom with RubyStats <DFF> @@ -31,7 +31,7 @@ Gem::Specification.new do |s| s.add_dependency 'redis', '>= 2.1' s.add_dependency 'sinatra', '>= 1.2.6' - s.add_dependency 'simple-random', '>= 0.9.3' + s.add_dependency 'rubystats', '>= 0.3.0' s.add_development_dependency 'bundler', '>= 1.17' s.add_development_dependency 'simplecov', '~> 0.15'
1
Replace usage of SimpleRandom with RubyStats
1
.gemspec
gemspec
mit
splitrb/split
10072065
<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.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.add_dependency 'redis', '>= 2.1' s.add_dependency 'sinatra', '>= 1.2.6' s.add_dependency 'simple-random', '>= 0.9.3' s.add_development_dependency 'bundler', '>= 1.17' s.add_development_dependency 'simplecov', '~> 0.15' 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> Replace usage of SimpleRandom with RubyStats <DFF> @@ -31,7 +31,7 @@ Gem::Specification.new do |s| s.add_dependency 'redis', '>= 2.1' s.add_dependency 'sinatra', '>= 1.2.6' - s.add_dependency 'simple-random', '>= 0.9.3' + s.add_dependency 'rubystats', '>= 0.3.0' s.add_development_dependency 'bundler', '>= 1.17' s.add_development_dependency 'simplecov', '~> 0.15'
1
Replace usage of SimpleRandom with RubyStats
1
.gemspec
gemspec
mit
splitrb/split
10072066
<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.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.add_dependency 'redis', '>= 2.1' s.add_dependency 'sinatra', '>= 1.2.6' s.add_dependency 'simple-random', '>= 0.9.3' s.add_development_dependency 'bundler', '>= 1.17' s.add_development_dependency 'simplecov', '~> 0.15' 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> Replace usage of SimpleRandom with RubyStats <DFF> @@ -31,7 +31,7 @@ Gem::Specification.new do |s| s.add_dependency 'redis', '>= 2.1' s.add_dependency 'sinatra', '>= 1.2.6' - s.add_dependency 'simple-random', '>= 0.9.3' + s.add_dependency 'rubystats', '>= 0.3.0' s.add_development_dependency 'bundler', '>= 1.17' s.add_development_dependency 'simplecov', '~> 0.15'
1
Replace usage of SimpleRandom with RubyStats
1
.gemspec
gemspec
mit
splitrb/split
10072067
<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 end end Split.configure {} if defined?(::Rails) class Split::Railtie < Rails::Railtie config.before_initialize { Split.configure { } } end else Split.configure { } end <MSG> Merge pull request #555 from husteadrobert/run_configure_after_initialize_on_rails Check to see if being run in Rails application and run in before_initialize <DFF> @@ -66,4 +66,11 @@ module Split end end -Split.configure {} +# 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 + Split.configure {} +end
8
Merge pull request #555 from husteadrobert/run_configure_after_initialize_on_rails
1
.rb
rb
mit
splitrb/split
10072068
<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 end end Split.configure {} if defined?(::Rails) class Split::Railtie < Rails::Railtie config.before_initialize { Split.configure { } } end else Split.configure { } end <MSG> Merge pull request #555 from husteadrobert/run_configure_after_initialize_on_rails Check to see if being run in Rails application and run in before_initialize <DFF> @@ -66,4 +66,11 @@ module Split end end -Split.configure {} +# 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 + Split.configure {} +end
8
Merge pull request #555 from husteadrobert/run_configure_after_initialize_on_rails
1
.rb
rb
mit
splitrb/split
10072069
<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 end end Split.configure {} if defined?(::Rails) class Split::Railtie < Rails::Railtie config.before_initialize { Split.configure { } } end else Split.configure { } end <MSG> Merge pull request #555 from husteadrobert/run_configure_after_initialize_on_rails Check to see if being run in Rails application and run in before_initialize <DFF> @@ -66,4 +66,11 @@ module Split end end -Split.configure {} +# 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 + Split.configure {} +end
8
Merge pull request #555 from husteadrobert/run_configure_after_initialize_on_rails
1
.rb
rb
mit
splitrb/split
10072070
<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.required_ruby_version = ">= 2.5.0" s.required_rubygems_version = ">= 2.0.0" s.add_development_dependency 'coveralls' s.add_development_dependency 'rack-test' s.add_development_dependency 'rake' s.add_development_dependency 'rspec', '~> 3.0' end 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> Lock rspec to 3.1.x for now <DFF> @@ -29,5 +29,5 @@ Gem::Specification.new do |s| s.add_development_dependency 'coveralls' s.add_development_dependency 'rack-test' s.add_development_dependency 'rake' - s.add_development_dependency 'rspec', '~> 3.0' + s.add_development_dependency 'rspec', '~> 3.1.0' end
1
Lock rspec to 3.1.x for now
1
.gemspec
gemspec
mit
splitrb/split
10072071
<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.required_ruby_version = ">= 2.5.0" s.required_rubygems_version = ">= 2.0.0" s.add_development_dependency 'coveralls' s.add_development_dependency 'rack-test' s.add_development_dependency 'rake' s.add_development_dependency 'rspec', '~> 3.0' end 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> Lock rspec to 3.1.x for now <DFF> @@ -29,5 +29,5 @@ Gem::Specification.new do |s| s.add_development_dependency 'coveralls' s.add_development_dependency 'rack-test' s.add_development_dependency 'rake' - s.add_development_dependency 'rspec', '~> 3.0' + s.add_development_dependency 'rspec', '~> 3.1.0' end
1
Lock rspec to 3.1.x for now
1
.gemspec
gemspec
mit
splitrb/split
10072072
<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.required_ruby_version = ">= 2.5.0" s.required_rubygems_version = ">= 2.0.0" s.add_development_dependency 'coveralls' s.add_development_dependency 'rack-test' s.add_development_dependency 'rake' s.add_development_dependency 'rspec', '~> 3.0' end 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> Lock rspec to 3.1.x for now <DFF> @@ -29,5 +29,5 @@ Gem::Specification.new do |s| s.add_development_dependency 'coveralls' s.add_development_dependency 'rack-test' s.add_development_dependency 'rake' - s.add_development_dependency 'rspec', '~> 3.0' + s.add_development_dependency 'rspec', '~> 3.1.0' end
1
Lock rspec to 3.1.x for now
1
.gemspec
gemspec
mit
splitrb/split
10072073
<NME> forms.py <BEF> import os from django import forms from django.conf import settings from djangopypi.models import Project, Classifier, Release from django.utils.translation import ugettext_lazy as _ class ProjectForm(forms.ModelForm): class Meta: model = Project exclude = ['owner', 'classifiers'] class ReleaseForm(forms.ModelForm): class Meta: model = Release exclude = ['project'] class SearchForm(forms.Form): search_value = forms.CharField(max_length=200) <MSG> Integrated djangopypi search engine - TODO: Functional Tests <DFF> @@ -14,8 +14,4 @@ class ProjectForm(forms.ModelForm): class ReleaseForm(forms.ModelForm): class Meta: model = Release - exclude = ['project'] - -class SearchForm(forms.Form): - search_value = forms.CharField(max_length=200) - + exclude = ['project'] \ No newline at end of file
1
Integrated djangopypi search engine - TODO: Functional Tests
5
.py
py
bsd-3-clause
ask/chishop
10072074
<NME> index.ts <BEF> import { Abbreviation } from '@emmetio/abbreviation'; import { CSSAbbreviation } from '@emmetio/css-abbreviation'; import parseMarkup, { stringify as stringifyMarkup } from './markup'; import parseStylesheet, { stringify as stringifyStylesheet, convertSnippets as parseStylesheetSnippets, CSSAbbreviationScope } from './stylesheet'; import resolveConfig, { UserConfig, Config } from './config'; export default function expandAbbreviation(abbr: string, config?: UserConfig): string { const resolvedConfig = resolveConfig(config); return resolvedConfig.type === 'stylesheet' ? stylesheet(abbr, resolvedConfig) : markup(abbr, resolvedConfig); } /** * Expands given *markup* abbreviation (e.g. regular Emmet abbreviation that * produces structured output like HTML) and outputs it according to options * provided in config */ export function markup(abbr: string | Abbreviation, config: Config) { return stringifyMarkup(parseMarkup(abbr, config), config); } /** * Expands given *stylesheet* abbreviation (a special Emmet abbreviation designed for * stylesheet languages like CSS, SASS etc.) and outputs it according to options * provided in config */ export function stylesheet(abbr: string | CSSAbbreviation, config: Config) { return stringifyStylesheet(parseStylesheet(abbr, config, snippets), config); } export { parseMarkup, stringifyMarkup, parseStylesheet, stringifyStylesheet, parseStylesheetSnippets }; export { default as extract, ExtractOptions, ExtractedAbbreviation } from './extract-abbreviation'; export { GlobalConfig, SyntaxType, Config, UserConfig, Options, default as resolveConfig } from './config'; export { default as extract, ExtractOptions, ExtractedAbbreviation } from './extract-abbreviation'; export { GlobalConfig, SyntaxType, Config, UserConfig, Options, AbbreviationContext, default as resolveConfig } from './config'; <MSG> Export abbreviation parsers from module <DFF> @@ -1,5 +1,5 @@ -import { Abbreviation } from '@emmetio/abbreviation'; -import { CSSAbbreviation } from '@emmetio/css-abbreviation'; +import markupAbbreviation, { Abbreviation } from '@emmetio/abbreviation'; +import stylesheetAbbreviation, { CSSAbbreviation } from '@emmetio/css-abbreviation'; import parseMarkup, { stringify as stringifyMarkup } from './markup'; import parseStylesheet, { stringify as stringifyStylesheet, @@ -33,6 +33,9 @@ export function stylesheet(abbr: string | CSSAbbreviation, config: Config, snipp return stringifyStylesheet(parseStylesheet(abbr, config, snippets), config); } -export { parseMarkup, stringifyMarkup, parseStylesheet, stringifyStylesheet, parseStylesheetSnippets }; +export { + markupAbbreviation, parseMarkup, stringifyMarkup, + stylesheetAbbreviation, parseStylesheet, stringifyStylesheet, parseStylesheetSnippets +}; export { default as extract, ExtractOptions, ExtractedAbbreviation } from './extract-abbreviation'; export { GlobalConfig, SyntaxType, Config, UserConfig, Options, default as resolveConfig } from './config';
6
Export abbreviation parsers from module
3
.ts
ts
mit
emmetio/emmet
10072075
<NME> index.ts <BEF> import { Abbreviation } from '@emmetio/abbreviation'; import { CSSAbbreviation } from '@emmetio/css-abbreviation'; import parseMarkup, { stringify as stringifyMarkup } from './markup'; import parseStylesheet, { stringify as stringifyStylesheet, convertSnippets as parseStylesheetSnippets, CSSAbbreviationScope } from './stylesheet'; import resolveConfig, { UserConfig, Config } from './config'; export default function expandAbbreviation(abbr: string, config?: UserConfig): string { const resolvedConfig = resolveConfig(config); return resolvedConfig.type === 'stylesheet' ? stylesheet(abbr, resolvedConfig) : markup(abbr, resolvedConfig); } /** * Expands given *markup* abbreviation (e.g. regular Emmet abbreviation that * produces structured output like HTML) and outputs it according to options * provided in config */ export function markup(abbr: string | Abbreviation, config: Config) { return stringifyMarkup(parseMarkup(abbr, config), config); } /** * Expands given *stylesheet* abbreviation (a special Emmet abbreviation designed for * stylesheet languages like CSS, SASS etc.) and outputs it according to options * provided in config */ export function stylesheet(abbr: string | CSSAbbreviation, config: Config) { return stringifyStylesheet(parseStylesheet(abbr, config, snippets), config); } export { parseMarkup, stringifyMarkup, parseStylesheet, stringifyStylesheet, parseStylesheetSnippets }; export { default as extract, ExtractOptions, ExtractedAbbreviation } from './extract-abbreviation'; export { GlobalConfig, SyntaxType, Config, UserConfig, Options, default as resolveConfig } from './config'; export { default as extract, ExtractOptions, ExtractedAbbreviation } from './extract-abbreviation'; export { GlobalConfig, SyntaxType, Config, UserConfig, Options, AbbreviationContext, default as resolveConfig } from './config'; <MSG> Export abbreviation parsers from module <DFF> @@ -1,5 +1,5 @@ -import { Abbreviation } from '@emmetio/abbreviation'; -import { CSSAbbreviation } from '@emmetio/css-abbreviation'; +import markupAbbreviation, { Abbreviation } from '@emmetio/abbreviation'; +import stylesheetAbbreviation, { CSSAbbreviation } from '@emmetio/css-abbreviation'; import parseMarkup, { stringify as stringifyMarkup } from './markup'; import parseStylesheet, { stringify as stringifyStylesheet, @@ -33,6 +33,9 @@ export function stylesheet(abbr: string | CSSAbbreviation, config: Config, snipp return stringifyStylesheet(parseStylesheet(abbr, config, snippets), config); } -export { parseMarkup, stringifyMarkup, parseStylesheet, stringifyStylesheet, parseStylesheetSnippets }; +export { + markupAbbreviation, parseMarkup, stringifyMarkup, + stylesheetAbbreviation, parseStylesheet, stringifyStylesheet, parseStylesheetSnippets +}; export { default as extract, ExtractOptions, ExtractedAbbreviation } from './extract-abbreviation'; export { GlobalConfig, SyntaxType, Config, UserConfig, Options, default as resolveConfig } from './config';
6
Export abbreviation parsers from module
3
.ts
ts
mit
emmetio/emmet
10072076
<NME> user.rb <BEF> # frozen_string_literal: true require "forwardable" module Split class User extend Forwardable def_delegators :@user, :keys, :[], :[]=, :delete attr_reader :user def initialize(context, adapter = nil) @user = adapter || Split::Persistence.adapter.new(context) @cleaned_up = false end def cleanup_old_experiments! return if @cleaned_up keys_without_finished(user.keys).each do |key| experiment = ExperimentCatalog.find key_without_version(key) if experiment.nil? || experiment.has_winner? || experiment.start_time.nil? user.delete key user.delete Experiment.finished_key(key) end end @cleaned_up = true end def max_experiments_reached?(experiment_key) if Split.configuration.allow_multiple_experiments == 'control' experiments = active_experiments experiment_key_without_version = key_without_version(experiment_key) count_control = experiments.count {|k, v| k == experiment_key_without_version || v == 'control'} experiments.size > count_control else !Split.configuration.allow_multiple_experiments && keys_without_experiment(user.keys, experiment_key).length > 0 end end def cleanup_old_versions!(experiment) keys = user.keys.select { |k| key_without_version(k) == experiment.name } keys_without_experiment(keys, experiment.key).each { |key| user.delete(key) } end def active_experiments experiment_pairs = {} keys_without_finished(user.keys).each do |key| Metric.possible_experiments(key_without_version(key)).each do |experiment| if !experiment.has_winner? experiment_pairs[key_without_version(key)] = user[key] end end end experiment_pairs end def self.find(user_id, adapter) adapter = adapter.is_a?(Symbol) ? Split::Persistence::ADAPTERS[adapter] : adapter if adapter.respond_to?(:find) User.new(nil, adapter.find(user_id)) else nil end end private def keys_without_experiment(keys, experiment_key) keys.reject { |k| k.match(Regexp.new("^#{experiment_key}(:finished)?$")) } end def keys_without_finished(keys) keys.reject { |k| k.include?(":finished") } end def key_without_version(key) key.split(/\:\d(?!\:)/)[0] end end end <MSG> Fix Layout/SpaceInsideBlockBraces <DFF> @@ -29,7 +29,7 @@ module Split if Split.configuration.allow_multiple_experiments == 'control' experiments = active_experiments experiment_key_without_version = key_without_version(experiment_key) - count_control = experiments.count {|k, v| k == experiment_key_without_version || v == 'control'} + count_control = experiments.count { |k, v| k == experiment_key_without_version || v == 'control' } experiments.size > count_control else !Split.configuration.allow_multiple_experiments &&
1
Fix Layout/SpaceInsideBlockBraces
1
.rb
rb
mit
splitrb/split
10072077
<NME> user.rb <BEF> # frozen_string_literal: true require "forwardable" module Split class User extend Forwardable def_delegators :@user, :keys, :[], :[]=, :delete attr_reader :user def initialize(context, adapter = nil) @user = adapter || Split::Persistence.adapter.new(context) @cleaned_up = false end def cleanup_old_experiments! return if @cleaned_up keys_without_finished(user.keys).each do |key| experiment = ExperimentCatalog.find key_without_version(key) if experiment.nil? || experiment.has_winner? || experiment.start_time.nil? user.delete key user.delete Experiment.finished_key(key) end end @cleaned_up = true end def max_experiments_reached?(experiment_key) if Split.configuration.allow_multiple_experiments == 'control' experiments = active_experiments experiment_key_without_version = key_without_version(experiment_key) count_control = experiments.count {|k, v| k == experiment_key_without_version || v == 'control'} experiments.size > count_control else !Split.configuration.allow_multiple_experiments && keys_without_experiment(user.keys, experiment_key).length > 0 end end def cleanup_old_versions!(experiment) keys = user.keys.select { |k| key_without_version(k) == experiment.name } keys_without_experiment(keys, experiment.key).each { |key| user.delete(key) } end def active_experiments experiment_pairs = {} keys_without_finished(user.keys).each do |key| Metric.possible_experiments(key_without_version(key)).each do |experiment| if !experiment.has_winner? experiment_pairs[key_without_version(key)] = user[key] end end end experiment_pairs end def self.find(user_id, adapter) adapter = adapter.is_a?(Symbol) ? Split::Persistence::ADAPTERS[adapter] : adapter if adapter.respond_to?(:find) User.new(nil, adapter.find(user_id)) else nil end end private def keys_without_experiment(keys, experiment_key) keys.reject { |k| k.match(Regexp.new("^#{experiment_key}(:finished)?$")) } end def keys_without_finished(keys) keys.reject { |k| k.include?(":finished") } end def key_without_version(key) key.split(/\:\d(?!\:)/)[0] end end end <MSG> Fix Layout/SpaceInsideBlockBraces <DFF> @@ -29,7 +29,7 @@ module Split if Split.configuration.allow_multiple_experiments == 'control' experiments = active_experiments experiment_key_without_version = key_without_version(experiment_key) - count_control = experiments.count {|k, v| k == experiment_key_without_version || v == 'control'} + count_control = experiments.count { |k, v| k == experiment_key_without_version || v == 'control' } experiments.size > count_control else !Split.configuration.allow_multiple_experiments &&
1
Fix Layout/SpaceInsideBlockBraces
1
.rb
rb
mit
splitrb/split
10072078
<NME> user.rb <BEF> # frozen_string_literal: true require "forwardable" module Split class User extend Forwardable def_delegators :@user, :keys, :[], :[]=, :delete attr_reader :user def initialize(context, adapter = nil) @user = adapter || Split::Persistence.adapter.new(context) @cleaned_up = false end def cleanup_old_experiments! return if @cleaned_up keys_without_finished(user.keys).each do |key| experiment = ExperimentCatalog.find key_without_version(key) if experiment.nil? || experiment.has_winner? || experiment.start_time.nil? user.delete key user.delete Experiment.finished_key(key) end end @cleaned_up = true end def max_experiments_reached?(experiment_key) if Split.configuration.allow_multiple_experiments == 'control' experiments = active_experiments experiment_key_without_version = key_without_version(experiment_key) count_control = experiments.count {|k, v| k == experiment_key_without_version || v == 'control'} experiments.size > count_control else !Split.configuration.allow_multiple_experiments && keys_without_experiment(user.keys, experiment_key).length > 0 end end def cleanup_old_versions!(experiment) keys = user.keys.select { |k| key_without_version(k) == experiment.name } keys_without_experiment(keys, experiment.key).each { |key| user.delete(key) } end def active_experiments experiment_pairs = {} keys_without_finished(user.keys).each do |key| Metric.possible_experiments(key_without_version(key)).each do |experiment| if !experiment.has_winner? experiment_pairs[key_without_version(key)] = user[key] end end end experiment_pairs end def self.find(user_id, adapter) adapter = adapter.is_a?(Symbol) ? Split::Persistence::ADAPTERS[adapter] : adapter if adapter.respond_to?(:find) User.new(nil, adapter.find(user_id)) else nil end end private def keys_without_experiment(keys, experiment_key) keys.reject { |k| k.match(Regexp.new("^#{experiment_key}(:finished)?$")) } end def keys_without_finished(keys) keys.reject { |k| k.include?(":finished") } end def key_without_version(key) key.split(/\:\d(?!\:)/)[0] end end end <MSG> Fix Layout/SpaceInsideBlockBraces <DFF> @@ -29,7 +29,7 @@ module Split if Split.configuration.allow_multiple_experiments == 'control' experiments = active_experiments experiment_key_without_version = key_without_version(experiment_key) - count_control = experiments.count {|k, v| k == experiment_key_without_version || v == 'control'} + count_control = experiments.count { |k, v| k == experiment_key_without_version || v == 'control' } experiments.size > count_control else !Split.configuration.allow_multiple_experiments &&
1
Fix Layout/SpaceInsideBlockBraces
1
.rb
rb
mit
splitrb/split
10072079
<NME> helper_spec.rb <BEF> # frozen_string_literal: true require "spec_helper" # TODO change some of these tests to use Rack::Test describe Split::Helper do include Split::Helper let(:experiment) { Split::ExperimentCatalog.find_or_create("link_color", "blue", "red") } describe "ab_test" do it "should not raise an error when passed strings for alternatives" do expect { ab_test("xyz", "1", "2", "3") }.not_to raise_error end it "should not raise an error when passed an array for alternatives" do expect { ab_test("xyz", ["1", "2", "3"]) }.not_to raise_error end it "should raise the appropriate error when passed integers for alternatives" do expect { ab_test("xyz", 1, 2, 3) }.to raise_error(ArgumentError) end it "should raise the appropriate error when passed symbols for alternatives" do expect { ab_test("xyz", :a, :b, :c) }.to raise_error(ArgumentError) end it "should not raise error when passed an array for goals" do expect { ab_test({ "link_color" => ["purchase", "refund"] }, "blue", "red") }.not_to raise_error end it "should not raise error when passed just one goal" do expect { ab_test({ "link_color" => "purchase" }, "blue", "red") }.not_to raise_error end it "raises an appropriate error when processing combined expirements" do Split.configuration.experiments = { combined_exp_1: { alternatives: [ { name: "control", percent: 50 }, { name: "test-alt", percent: 50 } ], metric: :my_metric, combined_experiments: [:combined_exp_1_sub_1] } } Split::ExperimentCatalog.find_or_create("combined_exp_1") expect { ab_test("combined_exp_1") }.to raise_error(Split::InvalidExperimentsFormatError) end it "should assign a random alternative to a new user when there are an equal number of alternatives assigned" do ab_test("link_color", "blue", "red") expect(["red", "blue"]).to include(ab_user["link_color"]) end it "should increment the participation counter after assignment to a new user" do previous_red_count = Split::Alternative.new("red", "link_color").participant_count previous_blue_count = Split::Alternative.new("blue", "link_color").participant_count ab_test("link_color", "blue", "red") new_red_count = Split::Alternative.new("red", "link_color").participant_count new_blue_count = Split::Alternative.new("blue", "link_color").participant_count expect((new_red_count + new_blue_count)).to eq(previous_red_count + previous_blue_count + 1) end it "should not increment the counter for an experiment that the user is not participating in" do ab_test("link_color", "blue", "red") e = Split::ExperimentCatalog.find_or_create("button_size", "small", "big") expect { # User shouldn't participate in this second experiment ab_test("button_size", "small", "big") }.not_to change { e.participant_count } end it "should not increment the counter for an ended experiment" do e = Split::ExperimentCatalog.find_or_create("button_size", "small", "big") e.winner = "small" expect { a = ab_test("button_size", "small", "big") expect(a).to eq("small") }.not_to change { e.participant_count } end it "should not increment the counter for an not started experiment" do expect(Split.configuration).to receive(:start_manually).and_return(true) e = Split::ExperimentCatalog.find_or_create("button_size", "small", "big") expect { a = ab_test("button_size", "small", "big") expect(a).to eq("small") }.not_to change { e.participant_count } end it "should return the given alternative for an existing user" do expect(ab_test("link_color", "blue", "red")).to eq ab_test("link_color", "blue", "red") end it "should always return the winner if one is present" do experiment.winner = "orange" expect(ab_test("link_color", "blue", "red")).to eq("orange") end it "should allow the alternative to be forced by passing it in the params" do # ?ab_test[link_color]=blue @params = { "ab_test" => { "link_color" => "blue" } } alternative = ab_test("link_color", "blue", "red") expect(alternative).to eq("blue") alternative = ab_test("link_color", { "blue" => 1 }, "red" => 5) expect(alternative).to eq("blue") @params = { "ab_test" => { "link_color" => "red" } } alternative = ab_test("link_color", "blue", "red") expect(alternative).to eq("red") alternative = ab_test("link_color", { "blue" => 5 }, "red" => 1) expect(alternative).to eq("red") end it "should not allow an arbitrary alternative" do @params = { "ab_test" => { "link_color" => "pink" } } alternative = ab_test("link_color", "blue") expect(alternative).to eq("blue") end it "should not store the split when a param forced alternative" do @params = { "ab_test" => { "link_color" => "blue" } } expect(ab_user).not_to receive(:[]=) ab_test("link_color", "blue", "red") end it "SPLIT_DISABLE query parameter should also force the alternative (uses control)" do @params = { "SPLIT_DISABLE" => "true" } alternative = ab_test("link_color", "blue", "red") expect(alternative).to eq("blue") alternative = ab_test("link_color", { "blue" => 1 }, "red" => 5) expect(alternative).to eq("blue") alternative = ab_test("link_color", "red", "blue") expect(alternative).to eq("red") alternative = ab_test("link_color", { "red" => 5 }, "blue" => 1) expect(alternative).to eq("red") end it "should not store the split when Split generically disabled" do @params = { "SPLIT_DISABLE" => "true" } expect(ab_user).not_to receive(:[]=) ab_test("link_color", "blue", "red") end context "when store_override is set" do before { Split.configuration.store_override = true } it "should store the forced alternative" do @params = { "ab_test" => { "link_color" => "blue" } } expect(ab_user).to receive(:[]=).with("link_color", "blue") ab_test("link_color", "blue", "red") end end context "when on_trial_choose is set" do before { Split.configuration.on_trial_choose = :some_method } it "should call the method" do expect(self).to receive(:some_method) ab_test("link_color", "blue", "red") end end it "should allow passing a block" do alt = ab_test("link_color", "blue", "red") ret = ab_test("link_color", "blue", "red") { |alternative| "shared/#{alternative}" } expect(ret).to eq("shared/#{alt}") end it "should allow the share of visitors see an alternative to be specified" do ab_test("link_color", { "blue" => 0.8 }, { "red" => 20 }) expect(["red", "blue"]).to include(ab_user["link_color"]) end it "should allow alternative weighting interface as a single hash" do ab_test("link_color", { "blue" => 0.01 }, "red" => 0.2) experiment = Split::ExperimentCatalog.find("link_color") expect(experiment.alternatives.map(&:name)).to eq(["blue", "red"]) expect(experiment.alternatives.collect { |a| a.weight }).to match_array([0.01, 0.2]) end it "should only let a user participate in one experiment at a time" do link_color = ab_test("link_color", "blue", "red") ab_test("button_size", "small", "big") expect(ab_user["link_color"]).to eq(link_color) big = Split::Alternative.new("big", "button_size") expect(big.participant_count).to eq(0) small = Split::Alternative.new("small", "button_size") expect(small.participant_count).to eq(0) end it "should let a user participate in many experiment with allow_multiple_experiments option" do Split.configure do |config| config.allow_multiple_experiments = true end link_color = ab_test("link_color", "blue", "red") button_size = ab_test("button_size", "small", "big") expect(ab_user["link_color"]).to eq(link_color) expect(ab_user["button_size"]).to eq(button_size) button_size_alt = Split::Alternative.new(button_size, "button_size") expect(button_size_alt.participant_count).to eq(1) end context "with allow_multiple_experiments = 'control'" do it "should let a user participate in many experiment with one non-'control' alternative" do Split.configure do |config| config.allow_multiple_experiments = "control" end groups = 100.times.map do |n| ab_test("test#{n}".to_sym, { "control" => (100 - n) }, { "test#{n}-alt" => n }) end experiments = ab_user.active_experiments expect(experiments.size).to be > 1 count_control = experiments.values.count { |g| g == "control" } expect(count_control).to eq(experiments.size - 1) count_alts = groups.count { |g| g != "control" } expect(count_alts).to eq(1) end context "when user already has experiment" do let(:mock_user) { Split::User.new(self, { "test_0" => "test-alt" }) } before do Split.configure do |config| config.allow_multiple_experiments = "control" end Split::ExperimentCatalog.find_or_initialize("test_0", "control", "test-alt").save Split::ExperimentCatalog.find_or_initialize("test_1", "control", "test-alt").save end it "should restore previously selected alternative" do expect(ab_user.active_experiments.size).to eq 1 expect(ab_test(:test_0, { "control" => 100 }, { "test-alt" => 1 })).to eq "test-alt" expect(ab_test(:test_0, { "control" => 1 }, { "test-alt" => 100 })).to eq "test-alt" end it "should select the correct alternatives after experiment resets" do experiment = Split::ExperimentCatalog.find(:test_0) experiment.reset mock_user[experiment.key] = "test-alt" expect(ab_user.active_experiments.size).to eq 1 expect(ab_test(:test_0, { "control" => 100 }, { "test-alt" => 1 })).to eq "test-alt" expect(ab_test(:test_0, { "control" => 0 }, { "test-alt" => 100 })).to eq "test-alt" end it "lets override existing choice" do pending "this requires user store reset on first call not depending on whelther it is current trial" @params = { "ab_test" => { "test_1" => "test-alt" } } expect(ab_test(:test_0, { "control" => 0 }, { "test-alt" => 100 })).to eq "control" expect(ab_test(:test_1, { "control" => 100 }, { "test-alt" => 1 })).to eq "test-alt" end end end it "should not over-write a finished key when an experiment is on a later version" do experiment.increment_version ab_user = { experiment.key => "blue", experiment.finished_key => true } finished_session = ab_user.dup ab_test("link_color", "blue", "red") expect(ab_user).to eq(finished_session) end end describe "metadata" do context "is defined" do before do Split.configuration.experiments = { my_experiment: { alternatives: ["one", "two"], resettable: false, metadata: { "one" => "Meta1", "two" => "Meta2" } } } end it "should be passed to helper block" do @params = { "ab_test" => { "my_experiment" => "two" } } expect(ab_test("my_experiment")).to eq "two" expect(ab_test("my_experiment") do |alternative, meta| meta end).to eq("Meta2") end describe 'ab_finished' 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 experiment that the user is not participating in' do ab_test('button_size', 'small', 'big') # 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(lambda { ab_finished('button_size') }).not_to change { Split::Alternative.new('small', 'button_size').completed_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' a = ab_test('button_size', 'small', 'big') expect(a).to eq('small') expect(lambda { 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 it "should do nothing where the experiment was not started by this user" do ab_user = nil expect(lambda { ab_finished('some_experiment_not_started_by_the_user') }).not_to raise_exception 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 alternative = ab_test("link_color", "blue", "red") expect(Split::Alternative.new(alternative, "link_color").participant_count).to eq(1) alternative = ab_test("button_size", "small", "big") expect(Split::Alternative.new(alternative, "button_size").participant_count).to eq(0) end it "should not increment the completed counter" do # So, user should be participating in the link_color experiment and # receive the control for button_size. As the user is not participating in # the button size experiment, finishing it should not increase the # completion count for that alternative. expect { ab_finished("button_size") }.not_to change { Split::Alternative.new("small", "button_size").completed_count } end end context "for an experiment that the user does not participate in" do before do Split::ExperimentCatalog.find_or_create(:not_started_experiment, "control", "alt") end it "should not raise an exception" do expect { ab_finished(:not_started_experiment) }.not_to raise_exception end it "should not change the user state when reset is false" do expect { ab_finished(:not_started_experiment, reset: false) }.not_to change { ab_user.keys }.from([]) end it "should not change the user state when reset is true" do expect(self).not_to receive(:reset!) ab_finished(:not_started_experiment) end it "should not increment the completed counter" do ab_finished(:not_started_experiment) expect(Split::Alternative.new("control", :not_started_experiment).completed_count).to eq(0) expect(Split::Alternative.new("alt", :not_started_experiment).completed_count).to eq(0) end end end context "finished with config" do it "passes reset option" do Split.configuration.experiments = { my_experiment: { alternatives: ["one", "two"], resettable: false, } } alternative = ab_test(:my_experiment) experiment = Split::ExperimentCatalog.find :my_experiment ab_finished :my_experiment expect(ab_user[experiment.key]).to eq(alternative) expect(ab_user[experiment.finished_key]).to eq(true) end end context "finished with metric name" do before { Split.configuration.experiments = {} } before { expect(Split::Alternative).to receive(:new).at_least(1).times.and_call_original } def should_finish_experiment(experiment_name, should_finish = true) alts = Split.configuration.experiments[experiment_name][:alternatives] experiment = Split::ExperimentCatalog.find_or_create(experiment_name, *alts) alt_name = ab_user[experiment.key] = alts.first alt = double("alternative") expect(alt).to receive(:name).at_most(1).times.and_return(alt_name) expect(Split::Alternative).to receive(:new).at_most(1).times.with(alt_name, experiment_name.to_s).and_return(alt) if should_finish expect(alt).to receive(:increment_completion).at_most(1).times else expect(alt).not_to receive(:increment_completion) end end it "completes the test" do Split.configuration.experiments[:my_experiment] = { alternatives: [ "control_opt", "other_opt" ], metric: :my_metric } should_finish_experiment :my_experiment ab_finished :my_metric end it "completes all relevant tests" do Split.configuration.experiments = { exp_1: { alternatives: [ "1-1", "1-2" ], metric: :my_metric }, exp_2: { alternatives: [ "2-1", "2-2" ], metric: :another_metric }, exp_3: { alternatives: [ "3-1", "3-2" ], metric: :my_metric }, } should_finish_experiment :exp_1 should_finish_experiment :exp_2, false should_finish_experiment :exp_3 ab_finished :my_metric end it "passes reset option" do Split.configuration.experiments = { my_exp: { alternatives: ["one", "two"], metric: :my_metric, resettable: false, } } alternative_name = ab_test(:my_exp) exp = Split::ExperimentCatalog.find :my_exp ab_finished :my_metric expect(ab_user[exp.key]).to eq(alternative_name) expect(ab_user[exp.finished_key]).to be_truthy end it "passes through options" do Split.configuration.experiments = { my_exp: { alternatives: ["one", "two"], metric: :my_metric, } } alternative_name = ab_test(:my_exp) exp = Split::ExperimentCatalog.find :my_exp ab_finished :my_metric, reset: false expect(ab_user[exp.key]).to eq(alternative_name) expect(ab_user[exp.finished_key]).to be_truthy end end describe "conversions" do it "should return a conversion rate for an alternative" do alternative_name = ab_test("link_color", "blue", "red") previous_convertion_rate = Split::Alternative.new(alternative_name, "link_color").conversion_rate expect(previous_convertion_rate).to eq(0.0) ab_finished("link_color") new_convertion_rate = Split::Alternative.new(alternative_name, "link_color").conversion_rate expect(new_convertion_rate).to eq(1.0) end end describe "active experiments" do it "should show an active test" do alternative = ab_test("def", "4", "5", "6") expect(active_experiments.count).to eq 1 expect(active_experiments.first[0]).to eq "def" expect(active_experiments.first[1]).to eq alternative end it "should show a finished test" do alternative = ab_test("def", "4", "5", "6") ab_finished("def", { reset: false }) expect(active_experiments.count).to eq 1 expect(active_experiments.first[0]).to eq "def" expect(active_experiments.first[1]).to eq alternative end it "should show an active test when an experiment is on a later version" do experiment.reset expect(experiment.version).to eq(1) ab_test("link_color", "blue", "red") expect(active_experiments.count).to eq 1 expect(active_experiments.first[0]).to eq "link_color" end it "should show versioned tests properly" do 10.times { experiment.reset } alternative = ab_test(experiment.name, "blue", "red") ab_finished(experiment.name, reset: false) expect(experiment.version).to eq(10) expect(active_experiments.count).to eq 1 expect(active_experiments).to eq({ "link_color" => alternative }) end it "should show multiple tests" do Split.configure do |config| config.allow_multiple_experiments = true end alternative = ab_test("def", "4", "5", "6") another_alternative = ab_test("ghi", "7", "8", "9") expect(active_experiments.count).to eq 2 expect(active_experiments["def"]).to eq alternative expect(active_experiments["ghi"]).to eq another_alternative end it "should not show tests with winners" do Split.configure do |config| config.allow_multiple_experiments = true end e = Split::ExperimentCatalog.find_or_create("def", "4", "5", "6") e.winner = "4" ab_test("def", "4", "5", "6") another_alternative = ab_test("ghi", "7", "8", "9") expect(active_experiments.count).to eq 1 expect(active_experiments.first[0]).to eq "ghi" expect(active_experiments.first[1]).to eq another_alternative end end describe "when user is a robot" do before(:each) do @request = OpenStruct.new(user_agent: "Googlebot/2.1 (+http://www.google.com/bot.html)") end describe "ab_test" do it "should return the control" do alternative = ab_test("link_color", "blue", "red") expect(alternative).to eq experiment.control.name end it "should not create a experiment" do ab_test("link_color", "blue", "red") expect(Split::Experiment.new("link_color")).to be_a_new_record end it "should not increment the participation count" do previous_red_count = Split::Alternative.new("red", "link_color").participant_count previous_blue_count = Split::Alternative.new("blue", "link_color").participant_count ab_test("link_color", "blue", "red") new_red_count = Split::Alternative.new("red", "link_color").participant_count new_blue_count = Split::Alternative.new("blue", "link_color").participant_count expect((new_red_count + new_blue_count)).to eq(previous_red_count + previous_blue_count) end end describe "finished" do it "should not increment the completed count" do alternative_name = ab_test("link_color", "blue", "red") previous_completion_count = Split::Alternative.new(alternative_name, "link_color").completed_count ab_finished("link_color") new_completion_count = Split::Alternative.new(alternative_name, "link_color").completed_count expect(new_completion_count).to eq(previous_completion_count) end end end describe "when providing custom ignore logic" do context "using a proc to configure custom logic" do before(:each) do Split.configure do |c| c.ignore_filter = proc { |request| true } # ignore everything end end it "ignores the ab_test" do ab_test("link_color", "blue", "red") red_count = Split::Alternative.new("red", "link_color").participant_count blue_count = Split::Alternative.new("blue", "link_color").participant_count expect((red_count + blue_count)).to be(0) end end end shared_examples_for "a disabled test" do describe "ab_test" do it "should return the control" do alternative = ab_test("link_color", "blue", "red") expect(alternative).to eq experiment.control.name end it "should not increment the participation count" do previous_red_count = Split::Alternative.new("red", "link_color").participant_count previous_blue_count = Split::Alternative.new("blue", "link_color").participant_count ab_test("link_color", "blue", "red") new_red_count = Split::Alternative.new("red", "link_color").participant_count new_blue_count = Split::Alternative.new("blue", "link_color").participant_count expect((new_red_count + new_blue_count)).to eq(previous_red_count + previous_blue_count) end end describe "finished" do it "should not increment the completed count" do alternative_name = ab_test("link_color", "blue", "red") previous_completion_count = Split::Alternative.new(alternative_name, "link_color").completed_count ab_finished("link_color") new_completion_count = Split::Alternative.new(alternative_name, "link_color").completed_count expect(new_completion_count).to eq(previous_completion_count) end end end describe "when ip address is ignored" do context "individually" do before(:each) do @request = OpenStruct.new(ip: "81.19.48.130") Split.configure do |c| c.ignore_ip_addresses << "81.19.48.130" end end it_behaves_like "a disabled test" end context "for a range" do before(:each) do @request = OpenStruct.new(ip: "81.19.48.129") Split.configure do |c| c.ignore_ip_addresses << /81\.19\.48\.[0-9]+/ end end it_behaves_like "a disabled test" end context "using both a range and a specific value" do before(:each) do @request = OpenStruct.new(ip: "81.19.48.128") Split.configure do |c| c.ignore_ip_addresses << "81.19.48.130" c.ignore_ip_addresses << /81\.19\.48\.[0-9]+/ end end it_behaves_like "a disabled test" end context "when ignored other address" do before do @request = OpenStruct.new(ip: "1.1.1.1") Split.configure do |c| c.ignore_ip_addresses << "81.19.48.130" end end it "works as usual" do alternative_name = ab_test("link_color", "red", "blue") expect { ab_finished("link_color") }.to change(Split::Alternative.new(alternative_name, "link_color"), :completed_count).by(1) end end end describe "when user is previewing" do before(:each) do @request = OpenStruct.new(headers: { "x-purpose" => "preview" }) end it_behaves_like "a disabled test" end describe "versioned experiments" do it "should use version zero if no version is present" do alternative_name = ab_test("link_color", "blue", "red") expect(experiment.version).to eq(0) expect(ab_user["link_color"]).to eq(alternative_name) end it "should save the version of the experiment to the session" do experiment.reset expect(experiment.version).to eq(1) alternative_name = ab_test("link_color", "blue", "red") expect(ab_user["link_color:1"]).to eq(alternative_name) end it "should load the experiment even if the version is not 0" do experiment.reset expect(experiment.version).to eq(1) alternative_name = ab_test("link_color", "blue", "red") expect(ab_user["link_color:1"]).to eq(alternative_name) return_alternative_name = ab_test("link_color", "blue", "red") expect(return_alternative_name).to eq(alternative_name) end it "should reset the session of a user on an older version of the experiment" do alternative_name = ab_test("link_color", "blue", "red") expect(ab_user["link_color"]).to eq(alternative_name) alternative = Split::Alternative.new(alternative_name, "link_color") expect(alternative.participant_count).to eq(1) experiment.reset expect(experiment.version).to eq(1) alternative = Split::Alternative.new(alternative_name, "link_color") expect(alternative.participant_count).to eq(0) new_alternative_name = ab_test("link_color", "blue", "red") expect(ab_user["link_color:1"]).to eq(new_alternative_name) new_alternative = Split::Alternative.new(new_alternative_name, "link_color") expect(new_alternative.participant_count).to eq(1) end it "should cleanup old versions of experiments from the session" do alternative_name = ab_test("link_color", "blue", "red") expect(ab_user["link_color"]).to eq(alternative_name) alternative = Split::Alternative.new(alternative_name, "link_color") expect(alternative.participant_count).to eq(1) experiment.reset expect(experiment.version).to eq(1) alternative = Split::Alternative.new(alternative_name, "link_color") expect(alternative.participant_count).to eq(0) new_alternative_name = ab_test("link_color", "blue", "red") expect(ab_user["link_color:1"]).to eq(new_alternative_name) end it "should only count completion of users on the current version" do alternative_name = ab_test("link_color", "blue", "red") expect(ab_user["link_color"]).to eq(alternative_name) Split::Alternative.new(alternative_name, "link_color") experiment.reset expect(experiment.version).to eq(1) ab_finished("link_color") alternative = Split::Alternative.new(alternative_name, "link_color") expect(alternative.completed_count).to eq(0) end end context "when redis is not available" do before(:each) do expect(Split).to receive(:redis).at_most(5).times.and_raise(Errno::ECONNREFUSED.new) end context "and db_failover config option is turned off" do before(:each) do Split.configure do |config| config.db_failover = false end end describe "ab_test" do it "should raise an exception" do expect { ab_test("link_color", "blue", "red") }.to raise_error(Errno::ECONNREFUSED) end end describe "finished" do it "should raise an exception" do expect { ab_finished("link_color") }.to raise_error(Errno::ECONNREFUSED) end end describe "disable split testing" do before(:each) do Split.configure do |config| config.enabled = false end end it "should not attempt to connect to redis" do expect { ab_test("link_color", "blue", "red") }.not_to raise_error end it "should return control variable" do expect(ab_test("link_color", "blue", "red")).to eq("blue") expect { ab_finished("link_color") }.not_to raise_error end end end context "and db_failover config option is turned on" do before(:each) do Split.configure do |config| config.db_failover = true end end describe "ab_test" do it "should not raise an exception" do expect { ab_test("link_color", "blue", "red") }.not_to raise_error end it "should call db_failover_on_db_error proc with error as parameter" do Split.configure do |config| config.db_failover_on_db_error = proc do |error| expect(error).to be_a(Errno::ECONNREFUSED) end end expect(Split.configuration.db_failover_on_db_error).to receive(:call).and_call_original ab_test("link_color", "blue", "red") end it "should always use first alternative" do expect(ab_test("link_color", "blue", "red")).to eq("blue") expect(ab_test("link_color", { "blue" => 0.01 }, "red" => 0.2)).to eq("blue") expect(ab_test("link_color", { "blue" => 0.8 }, { "red" => 20 })).to eq("blue") expect(ab_test("link_color", "blue", "red") do |alternative| "shared/#{alternative}" end).to eq("shared/blue") end context "and db_failover_allow_parameter_override config option is turned on" do before(:each) do Split.configure do |config| config.db_failover_allow_parameter_override = true end end context "and given an override parameter" do it "should use given override instead of the first alternative" do @params = { "ab_test" => { "link_color" => "red" } } expect(ab_test("link_color", "blue", "red")).to eq("red") expect(ab_test("link_color", "blue", "red", "green")).to eq("red") expect(ab_test("link_color", { "blue" => 0.01 }, "red" => 0.2)).to eq("red") expect(ab_test("link_color", { "blue" => 0.8 }, { "red" => 20 })).to eq("red") expect(ab_test("link_color", "blue", "red") do |alternative| "shared/#{alternative}" end).to eq("shared/red") end end end context "and preloaded config given" do before do Split.configuration.experiments[:link_color] = { alternatives: [ "blue", "red" ], } end it "uses first alternative" do expect(ab_test(:link_color)).to eq("blue") end end end describe "finished" do it "should not raise an exception" do expect { ab_finished("link_color") }.not_to raise_error end it "should call db_failover_on_db_error proc with error as parameter" do Split.configure do |config| config.db_failover_on_db_error = proc do |error| expect(error).to be_a(Errno::ECONNREFUSED) end end expect(Split.configuration.db_failover_on_db_error).to receive(:call).and_call_original ab_finished("link_color") end end end end context "with preloaded config" do before { Split.configuration.experiments = {} } it "pulls options from config file" do Split.configuration.experiments[:my_experiment] = { alternatives: [ "control_opt", "other_opt" ], goals: ["goal1", "goal2"] } ab_test :my_experiment expect(Split::Experiment.new(:my_experiment).alternatives.map(&:name)).to eq([ "control_opt", "other_opt" ]) expect(Split::Experiment.new(:my_experiment).goals).to eq([ "goal1", "goal2" ]) end it "can be called multiple times" do Split.configuration.experiments[:my_experiment] = { alternatives: [ "control_opt", "other_opt" ], goals: ["goal1", "goal2"] } 5.times { ab_test :my_experiment } experiment = Split::Experiment.new(:my_experiment) expect(experiment.alternatives.map(&:name)).to eq([ "control_opt", "other_opt" ]) expect(experiment.goals).to eq([ "goal1", "goal2" ]) expect(experiment.participant_count).to eq(1) end it "accepts multiple goals" do Split.configuration.experiments[:my_experiment] = { alternatives: [ "control_opt", "other_opt" ], goals: [ "goal1", "goal2", "goal3" ] } ab_test :my_experiment experiment = Split::Experiment.new(:my_experiment) expect(experiment.goals).to eq([ "goal1", "goal2", "goal3" ]) end it "allow specifying goals to be optional" do Split.configuration.experiments[:my_experiment] = { alternatives: [ "control_opt", "other_opt" ] } experiment = Split::Experiment.new(:my_experiment) expect(experiment.goals).to eq([]) end it "accepts multiple alternatives" do Split.configuration.experiments[:my_experiment] = { alternatives: [ "control_opt", "second_opt", "third_opt" ], } ab_test :my_experiment experiment = Split::Experiment.new(:my_experiment) expect(experiment.alternatives.map(&:name)).to eq([ "control_opt", "second_opt", "third_opt" ]) end it "accepts probability on alternatives" do Split.configuration.experiments[:my_experiment] = { alternatives: [ { name: "control_opt", percent: 67 }, { name: "second_opt", percent: 10 }, { name: "third_opt", percent: 23 }, ], } ab_test :my_experiment experiment = Split::Experiment.new(:my_experiment) expect(experiment.alternatives.collect { |a| [a.name, a.weight] }).to eq([["control_opt", 0.67], ["second_opt", 0.1], ["third_opt", 0.23]]) end it "accepts probability on some alternatives" do Split.configuration.experiments[:my_experiment] = { alternatives: [ { name: "control_opt", percent: 34 }, "second_opt", { name: "third_opt", percent: 23 }, "fourth_opt", ], } ab_test :my_experiment experiment = Split::Experiment.new(:my_experiment) names_and_weights = experiment.alternatives.collect { |a| [a.name, a.weight] } expect(names_and_weights).to eq([["control_opt", 0.34], ["second_opt", 0.215], ["third_opt", 0.23], ["fourth_opt", 0.215]]) expect(names_and_weights.inject(0) { |sum, nw| sum + nw[1] }).to eq(1.0) end it "allows name param without probability" do Split.configuration.experiments[:my_experiment] = { alternatives: [ { name: "control_opt" }, "second_opt", { name: "third_opt", percent: 64 }, ], } ab_test :my_experiment experiment = Split::Experiment.new(:my_experiment) names_and_weights = experiment.alternatives.collect { |a| [a.name, a.weight] } expect(names_and_weights).to eq([["control_opt", 0.18], ["second_opt", 0.18], ["third_opt", 0.64]]) expect(names_and_weights.inject(0) { |sum, nw| sum + nw[1] }).to eq(1.0) end it "fails gracefully if config is missing experiment" do Split.configuration.experiments = { other_experiment: { foo: "Bar" } } expect { ab_test :my_experiment }.to raise_error(Split::ExperimentNotFound) end it "fails gracefully if config is missing" do expect { Split.configuration.experiments = nil }.to raise_error(Split::InvalidExperimentsFormatError) end it "fails gracefully if config is missing alternatives" do Split.configuration.experiments[:my_experiment] = { foo: "Bar" } expect { ab_test :my_experiment }.to raise_error(NoMethodError) end end it "should handle multiple experiments correctly" do experiment2 = Split::ExperimentCatalog.find_or_create("link_color2", "blue", "red") ab_test("link_color", "blue", "red") ab_test("link_color2", "blue", "red") ab_finished("link_color2") experiment2.alternatives.each do |alt| expect(alt.unfinished_count).to eq(0) end end context "with goals" do before do @experiment = { "link_color" => ["purchase", "refund"] } @alternatives = ["blue", "red"] @experiment_name, @goals = normalize_metric(@experiment) @goal1 = @goals[0] @goal2 = @goals[1] end it "should normalize experiment" do expect(@experiment_name).to eq("link_color") expect(@goals).to eq(["purchase", "refund"]) end describe "ab_test" do it "should allow experiment goals interface as a single hash" do ab_test(@experiment, *@alternatives) experiment = Split::ExperimentCatalog.find("link_color") expect(experiment.goals).to eq(["purchase", "refund"]) end end describe "ab_finished" do before do @alternative_name = ab_test(@experiment, *@alternatives) end it "should increment the counter for the specified-goal completed alternative" do expect { ab_finished({ "link_color" => ["purchase"] }) } .to change { Split::Alternative.new(@alternative_name, @experiment_name).completed_count(@goal2) }.by(0) .and change { Split::Alternative.new(@alternative_name, @experiment_name).completed_count(@goal1) }.by(1) end end end end <MSG> Merge pull request #577 from gnanou/finish_inactive_experiment Handle correctly case when ab_finished is called before ab_test for a user <DFF> @@ -296,98 +296,126 @@ describe Split::Helper do end describe 'ab_finished' 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 + 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 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 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 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 experiment that the user is not participating in' do - ab_test('button_size', 'small', 'big') + 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(lambda { + ab_finished('button_size') + }).not_to change { Split::Alternative.new(a, 'button_size').completed_count } + end - # 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(lambda { - ab_finished('button_size') - }).not_to change { Split::Alternative.new('small', '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 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(lambda { - ab_finished('button_size') - }).not_to change { Split::Alternative.new(a, 'button_size').completed_count } - 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 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 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 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 versioned" do + @experiment.increment_version + @alternative_name = ab_test(@experiment_name, *@alternatives) - 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 + 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) + 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 - expect(ab_user[@experiment.key]).to eq(@alternative_name) - ab_finished(@experiment_name) - expect(ab_user.keys).to be_empty + 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 - it "should do nothing where the experiment was not started by this user" do - ab_user = nil - expect(lambda { ab_finished('some_experiment_not_started_by_the_user') }).not_to raise_exception + 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(lambda { + ab_finished('button_size') + }).not_to change { Split::Alternative.new('small', 'button_size').completed_count } + end 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) + 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 call the method without alternative" do - ab_user[@experiment.key] = nil - expect(self).not_to receive(:some_method) - ab_finished(@experiment_name) + 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
103
Merge pull request #577 from gnanou/finish_inactive_experiment
75
.rb
rb
mit
splitrb/split
10072080
<NME> helper_spec.rb <BEF> # frozen_string_literal: true require "spec_helper" # TODO change some of these tests to use Rack::Test describe Split::Helper do include Split::Helper let(:experiment) { Split::ExperimentCatalog.find_or_create("link_color", "blue", "red") } describe "ab_test" do it "should not raise an error when passed strings for alternatives" do expect { ab_test("xyz", "1", "2", "3") }.not_to raise_error end it "should not raise an error when passed an array for alternatives" do expect { ab_test("xyz", ["1", "2", "3"]) }.not_to raise_error end it "should raise the appropriate error when passed integers for alternatives" do expect { ab_test("xyz", 1, 2, 3) }.to raise_error(ArgumentError) end it "should raise the appropriate error when passed symbols for alternatives" do expect { ab_test("xyz", :a, :b, :c) }.to raise_error(ArgumentError) end it "should not raise error when passed an array for goals" do expect { ab_test({ "link_color" => ["purchase", "refund"] }, "blue", "red") }.not_to raise_error end it "should not raise error when passed just one goal" do expect { ab_test({ "link_color" => "purchase" }, "blue", "red") }.not_to raise_error end it "raises an appropriate error when processing combined expirements" do Split.configuration.experiments = { combined_exp_1: { alternatives: [ { name: "control", percent: 50 }, { name: "test-alt", percent: 50 } ], metric: :my_metric, combined_experiments: [:combined_exp_1_sub_1] } } Split::ExperimentCatalog.find_or_create("combined_exp_1") expect { ab_test("combined_exp_1") }.to raise_error(Split::InvalidExperimentsFormatError) end it "should assign a random alternative to a new user when there are an equal number of alternatives assigned" do ab_test("link_color", "blue", "red") expect(["red", "blue"]).to include(ab_user["link_color"]) end it "should increment the participation counter after assignment to a new user" do previous_red_count = Split::Alternative.new("red", "link_color").participant_count previous_blue_count = Split::Alternative.new("blue", "link_color").participant_count ab_test("link_color", "blue", "red") new_red_count = Split::Alternative.new("red", "link_color").participant_count new_blue_count = Split::Alternative.new("blue", "link_color").participant_count expect((new_red_count + new_blue_count)).to eq(previous_red_count + previous_blue_count + 1) end it "should not increment the counter for an experiment that the user is not participating in" do ab_test("link_color", "blue", "red") e = Split::ExperimentCatalog.find_or_create("button_size", "small", "big") expect { # User shouldn't participate in this second experiment ab_test("button_size", "small", "big") }.not_to change { e.participant_count } end it "should not increment the counter for an ended experiment" do e = Split::ExperimentCatalog.find_or_create("button_size", "small", "big") e.winner = "small" expect { a = ab_test("button_size", "small", "big") expect(a).to eq("small") }.not_to change { e.participant_count } end it "should not increment the counter for an not started experiment" do expect(Split.configuration).to receive(:start_manually).and_return(true) e = Split::ExperimentCatalog.find_or_create("button_size", "small", "big") expect { a = ab_test("button_size", "small", "big") expect(a).to eq("small") }.not_to change { e.participant_count } end it "should return the given alternative for an existing user" do expect(ab_test("link_color", "blue", "red")).to eq ab_test("link_color", "blue", "red") end it "should always return the winner if one is present" do experiment.winner = "orange" expect(ab_test("link_color", "blue", "red")).to eq("orange") end it "should allow the alternative to be forced by passing it in the params" do # ?ab_test[link_color]=blue @params = { "ab_test" => { "link_color" => "blue" } } alternative = ab_test("link_color", "blue", "red") expect(alternative).to eq("blue") alternative = ab_test("link_color", { "blue" => 1 }, "red" => 5) expect(alternative).to eq("blue") @params = { "ab_test" => { "link_color" => "red" } } alternative = ab_test("link_color", "blue", "red") expect(alternative).to eq("red") alternative = ab_test("link_color", { "blue" => 5 }, "red" => 1) expect(alternative).to eq("red") end it "should not allow an arbitrary alternative" do @params = { "ab_test" => { "link_color" => "pink" } } alternative = ab_test("link_color", "blue") expect(alternative).to eq("blue") end it "should not store the split when a param forced alternative" do @params = { "ab_test" => { "link_color" => "blue" } } expect(ab_user).not_to receive(:[]=) ab_test("link_color", "blue", "red") end it "SPLIT_DISABLE query parameter should also force the alternative (uses control)" do @params = { "SPLIT_DISABLE" => "true" } alternative = ab_test("link_color", "blue", "red") expect(alternative).to eq("blue") alternative = ab_test("link_color", { "blue" => 1 }, "red" => 5) expect(alternative).to eq("blue") alternative = ab_test("link_color", "red", "blue") expect(alternative).to eq("red") alternative = ab_test("link_color", { "red" => 5 }, "blue" => 1) expect(alternative).to eq("red") end it "should not store the split when Split generically disabled" do @params = { "SPLIT_DISABLE" => "true" } expect(ab_user).not_to receive(:[]=) ab_test("link_color", "blue", "red") end context "when store_override is set" do before { Split.configuration.store_override = true } it "should store the forced alternative" do @params = { "ab_test" => { "link_color" => "blue" } } expect(ab_user).to receive(:[]=).with("link_color", "blue") ab_test("link_color", "blue", "red") end end context "when on_trial_choose is set" do before { Split.configuration.on_trial_choose = :some_method } it "should call the method" do expect(self).to receive(:some_method) ab_test("link_color", "blue", "red") end end it "should allow passing a block" do alt = ab_test("link_color", "blue", "red") ret = ab_test("link_color", "blue", "red") { |alternative| "shared/#{alternative}" } expect(ret).to eq("shared/#{alt}") end it "should allow the share of visitors see an alternative to be specified" do ab_test("link_color", { "blue" => 0.8 }, { "red" => 20 }) expect(["red", "blue"]).to include(ab_user["link_color"]) end it "should allow alternative weighting interface as a single hash" do ab_test("link_color", { "blue" => 0.01 }, "red" => 0.2) experiment = Split::ExperimentCatalog.find("link_color") expect(experiment.alternatives.map(&:name)).to eq(["blue", "red"]) expect(experiment.alternatives.collect { |a| a.weight }).to match_array([0.01, 0.2]) end it "should only let a user participate in one experiment at a time" do link_color = ab_test("link_color", "blue", "red") ab_test("button_size", "small", "big") expect(ab_user["link_color"]).to eq(link_color) big = Split::Alternative.new("big", "button_size") expect(big.participant_count).to eq(0) small = Split::Alternative.new("small", "button_size") expect(small.participant_count).to eq(0) end it "should let a user participate in many experiment with allow_multiple_experiments option" do Split.configure do |config| config.allow_multiple_experiments = true end link_color = ab_test("link_color", "blue", "red") button_size = ab_test("button_size", "small", "big") expect(ab_user["link_color"]).to eq(link_color) expect(ab_user["button_size"]).to eq(button_size) button_size_alt = Split::Alternative.new(button_size, "button_size") expect(button_size_alt.participant_count).to eq(1) end context "with allow_multiple_experiments = 'control'" do it "should let a user participate in many experiment with one non-'control' alternative" do Split.configure do |config| config.allow_multiple_experiments = "control" end groups = 100.times.map do |n| ab_test("test#{n}".to_sym, { "control" => (100 - n) }, { "test#{n}-alt" => n }) end experiments = ab_user.active_experiments expect(experiments.size).to be > 1 count_control = experiments.values.count { |g| g == "control" } expect(count_control).to eq(experiments.size - 1) count_alts = groups.count { |g| g != "control" } expect(count_alts).to eq(1) end context "when user already has experiment" do let(:mock_user) { Split::User.new(self, { "test_0" => "test-alt" }) } before do Split.configure do |config| config.allow_multiple_experiments = "control" end Split::ExperimentCatalog.find_or_initialize("test_0", "control", "test-alt").save Split::ExperimentCatalog.find_or_initialize("test_1", "control", "test-alt").save end it "should restore previously selected alternative" do expect(ab_user.active_experiments.size).to eq 1 expect(ab_test(:test_0, { "control" => 100 }, { "test-alt" => 1 })).to eq "test-alt" expect(ab_test(:test_0, { "control" => 1 }, { "test-alt" => 100 })).to eq "test-alt" end it "should select the correct alternatives after experiment resets" do experiment = Split::ExperimentCatalog.find(:test_0) experiment.reset mock_user[experiment.key] = "test-alt" expect(ab_user.active_experiments.size).to eq 1 expect(ab_test(:test_0, { "control" => 100 }, { "test-alt" => 1 })).to eq "test-alt" expect(ab_test(:test_0, { "control" => 0 }, { "test-alt" => 100 })).to eq "test-alt" end it "lets override existing choice" do pending "this requires user store reset on first call not depending on whelther it is current trial" @params = { "ab_test" => { "test_1" => "test-alt" } } expect(ab_test(:test_0, { "control" => 0 }, { "test-alt" => 100 })).to eq "control" expect(ab_test(:test_1, { "control" => 100 }, { "test-alt" => 1 })).to eq "test-alt" end end end it "should not over-write a finished key when an experiment is on a later version" do experiment.increment_version ab_user = { experiment.key => "blue", experiment.finished_key => true } finished_session = ab_user.dup ab_test("link_color", "blue", "red") expect(ab_user).to eq(finished_session) end end describe "metadata" do context "is defined" do before do Split.configuration.experiments = { my_experiment: { alternatives: ["one", "two"], resettable: false, metadata: { "one" => "Meta1", "two" => "Meta2" } } } end it "should be passed to helper block" do @params = { "ab_test" => { "my_experiment" => "two" } } expect(ab_test("my_experiment")).to eq "two" expect(ab_test("my_experiment") do |alternative, meta| meta end).to eq("Meta2") end describe 'ab_finished' 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 experiment that the user is not participating in' do ab_test('button_size', 'small', 'big') # 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(lambda { ab_finished('button_size') }).not_to change { Split::Alternative.new('small', 'button_size').completed_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' a = ab_test('button_size', 'small', 'big') expect(a).to eq('small') expect(lambda { 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 it "should do nothing where the experiment was not started by this user" do ab_user = nil expect(lambda { ab_finished('some_experiment_not_started_by_the_user') }).not_to raise_exception 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 alternative = ab_test("link_color", "blue", "red") expect(Split::Alternative.new(alternative, "link_color").participant_count).to eq(1) alternative = ab_test("button_size", "small", "big") expect(Split::Alternative.new(alternative, "button_size").participant_count).to eq(0) end it "should not increment the completed counter" do # So, user should be participating in the link_color experiment and # receive the control for button_size. As the user is not participating in # the button size experiment, finishing it should not increase the # completion count for that alternative. expect { ab_finished("button_size") }.not_to change { Split::Alternative.new("small", "button_size").completed_count } end end context "for an experiment that the user does not participate in" do before do Split::ExperimentCatalog.find_or_create(:not_started_experiment, "control", "alt") end it "should not raise an exception" do expect { ab_finished(:not_started_experiment) }.not_to raise_exception end it "should not change the user state when reset is false" do expect { ab_finished(:not_started_experiment, reset: false) }.not_to change { ab_user.keys }.from([]) end it "should not change the user state when reset is true" do expect(self).not_to receive(:reset!) ab_finished(:not_started_experiment) end it "should not increment the completed counter" do ab_finished(:not_started_experiment) expect(Split::Alternative.new("control", :not_started_experiment).completed_count).to eq(0) expect(Split::Alternative.new("alt", :not_started_experiment).completed_count).to eq(0) end end end context "finished with config" do it "passes reset option" do Split.configuration.experiments = { my_experiment: { alternatives: ["one", "two"], resettable: false, } } alternative = ab_test(:my_experiment) experiment = Split::ExperimentCatalog.find :my_experiment ab_finished :my_experiment expect(ab_user[experiment.key]).to eq(alternative) expect(ab_user[experiment.finished_key]).to eq(true) end end context "finished with metric name" do before { Split.configuration.experiments = {} } before { expect(Split::Alternative).to receive(:new).at_least(1).times.and_call_original } def should_finish_experiment(experiment_name, should_finish = true) alts = Split.configuration.experiments[experiment_name][:alternatives] experiment = Split::ExperimentCatalog.find_or_create(experiment_name, *alts) alt_name = ab_user[experiment.key] = alts.first alt = double("alternative") expect(alt).to receive(:name).at_most(1).times.and_return(alt_name) expect(Split::Alternative).to receive(:new).at_most(1).times.with(alt_name, experiment_name.to_s).and_return(alt) if should_finish expect(alt).to receive(:increment_completion).at_most(1).times else expect(alt).not_to receive(:increment_completion) end end it "completes the test" do Split.configuration.experiments[:my_experiment] = { alternatives: [ "control_opt", "other_opt" ], metric: :my_metric } should_finish_experiment :my_experiment ab_finished :my_metric end it "completes all relevant tests" do Split.configuration.experiments = { exp_1: { alternatives: [ "1-1", "1-2" ], metric: :my_metric }, exp_2: { alternatives: [ "2-1", "2-2" ], metric: :another_metric }, exp_3: { alternatives: [ "3-1", "3-2" ], metric: :my_metric }, } should_finish_experiment :exp_1 should_finish_experiment :exp_2, false should_finish_experiment :exp_3 ab_finished :my_metric end it "passes reset option" do Split.configuration.experiments = { my_exp: { alternatives: ["one", "two"], metric: :my_metric, resettable: false, } } alternative_name = ab_test(:my_exp) exp = Split::ExperimentCatalog.find :my_exp ab_finished :my_metric expect(ab_user[exp.key]).to eq(alternative_name) expect(ab_user[exp.finished_key]).to be_truthy end it "passes through options" do Split.configuration.experiments = { my_exp: { alternatives: ["one", "two"], metric: :my_metric, } } alternative_name = ab_test(:my_exp) exp = Split::ExperimentCatalog.find :my_exp ab_finished :my_metric, reset: false expect(ab_user[exp.key]).to eq(alternative_name) expect(ab_user[exp.finished_key]).to be_truthy end end describe "conversions" do it "should return a conversion rate for an alternative" do alternative_name = ab_test("link_color", "blue", "red") previous_convertion_rate = Split::Alternative.new(alternative_name, "link_color").conversion_rate expect(previous_convertion_rate).to eq(0.0) ab_finished("link_color") new_convertion_rate = Split::Alternative.new(alternative_name, "link_color").conversion_rate expect(new_convertion_rate).to eq(1.0) end end describe "active experiments" do it "should show an active test" do alternative = ab_test("def", "4", "5", "6") expect(active_experiments.count).to eq 1 expect(active_experiments.first[0]).to eq "def" expect(active_experiments.first[1]).to eq alternative end it "should show a finished test" do alternative = ab_test("def", "4", "5", "6") ab_finished("def", { reset: false }) expect(active_experiments.count).to eq 1 expect(active_experiments.first[0]).to eq "def" expect(active_experiments.first[1]).to eq alternative end it "should show an active test when an experiment is on a later version" do experiment.reset expect(experiment.version).to eq(1) ab_test("link_color", "blue", "red") expect(active_experiments.count).to eq 1 expect(active_experiments.first[0]).to eq "link_color" end it "should show versioned tests properly" do 10.times { experiment.reset } alternative = ab_test(experiment.name, "blue", "red") ab_finished(experiment.name, reset: false) expect(experiment.version).to eq(10) expect(active_experiments.count).to eq 1 expect(active_experiments).to eq({ "link_color" => alternative }) end it "should show multiple tests" do Split.configure do |config| config.allow_multiple_experiments = true end alternative = ab_test("def", "4", "5", "6") another_alternative = ab_test("ghi", "7", "8", "9") expect(active_experiments.count).to eq 2 expect(active_experiments["def"]).to eq alternative expect(active_experiments["ghi"]).to eq another_alternative end it "should not show tests with winners" do Split.configure do |config| config.allow_multiple_experiments = true end e = Split::ExperimentCatalog.find_or_create("def", "4", "5", "6") e.winner = "4" ab_test("def", "4", "5", "6") another_alternative = ab_test("ghi", "7", "8", "9") expect(active_experiments.count).to eq 1 expect(active_experiments.first[0]).to eq "ghi" expect(active_experiments.first[1]).to eq another_alternative end end describe "when user is a robot" do before(:each) do @request = OpenStruct.new(user_agent: "Googlebot/2.1 (+http://www.google.com/bot.html)") end describe "ab_test" do it "should return the control" do alternative = ab_test("link_color", "blue", "red") expect(alternative).to eq experiment.control.name end it "should not create a experiment" do ab_test("link_color", "blue", "red") expect(Split::Experiment.new("link_color")).to be_a_new_record end it "should not increment the participation count" do previous_red_count = Split::Alternative.new("red", "link_color").participant_count previous_blue_count = Split::Alternative.new("blue", "link_color").participant_count ab_test("link_color", "blue", "red") new_red_count = Split::Alternative.new("red", "link_color").participant_count new_blue_count = Split::Alternative.new("blue", "link_color").participant_count expect((new_red_count + new_blue_count)).to eq(previous_red_count + previous_blue_count) end end describe "finished" do it "should not increment the completed count" do alternative_name = ab_test("link_color", "blue", "red") previous_completion_count = Split::Alternative.new(alternative_name, "link_color").completed_count ab_finished("link_color") new_completion_count = Split::Alternative.new(alternative_name, "link_color").completed_count expect(new_completion_count).to eq(previous_completion_count) end end end describe "when providing custom ignore logic" do context "using a proc to configure custom logic" do before(:each) do Split.configure do |c| c.ignore_filter = proc { |request| true } # ignore everything end end it "ignores the ab_test" do ab_test("link_color", "blue", "red") red_count = Split::Alternative.new("red", "link_color").participant_count blue_count = Split::Alternative.new("blue", "link_color").participant_count expect((red_count + blue_count)).to be(0) end end end shared_examples_for "a disabled test" do describe "ab_test" do it "should return the control" do alternative = ab_test("link_color", "blue", "red") expect(alternative).to eq experiment.control.name end it "should not increment the participation count" do previous_red_count = Split::Alternative.new("red", "link_color").participant_count previous_blue_count = Split::Alternative.new("blue", "link_color").participant_count ab_test("link_color", "blue", "red") new_red_count = Split::Alternative.new("red", "link_color").participant_count new_blue_count = Split::Alternative.new("blue", "link_color").participant_count expect((new_red_count + new_blue_count)).to eq(previous_red_count + previous_blue_count) end end describe "finished" do it "should not increment the completed count" do alternative_name = ab_test("link_color", "blue", "red") previous_completion_count = Split::Alternative.new(alternative_name, "link_color").completed_count ab_finished("link_color") new_completion_count = Split::Alternative.new(alternative_name, "link_color").completed_count expect(new_completion_count).to eq(previous_completion_count) end end end describe "when ip address is ignored" do context "individually" do before(:each) do @request = OpenStruct.new(ip: "81.19.48.130") Split.configure do |c| c.ignore_ip_addresses << "81.19.48.130" end end it_behaves_like "a disabled test" end context "for a range" do before(:each) do @request = OpenStruct.new(ip: "81.19.48.129") Split.configure do |c| c.ignore_ip_addresses << /81\.19\.48\.[0-9]+/ end end it_behaves_like "a disabled test" end context "using both a range and a specific value" do before(:each) do @request = OpenStruct.new(ip: "81.19.48.128") Split.configure do |c| c.ignore_ip_addresses << "81.19.48.130" c.ignore_ip_addresses << /81\.19\.48\.[0-9]+/ end end it_behaves_like "a disabled test" end context "when ignored other address" do before do @request = OpenStruct.new(ip: "1.1.1.1") Split.configure do |c| c.ignore_ip_addresses << "81.19.48.130" end end it "works as usual" do alternative_name = ab_test("link_color", "red", "blue") expect { ab_finished("link_color") }.to change(Split::Alternative.new(alternative_name, "link_color"), :completed_count).by(1) end end end describe "when user is previewing" do before(:each) do @request = OpenStruct.new(headers: { "x-purpose" => "preview" }) end it_behaves_like "a disabled test" end describe "versioned experiments" do it "should use version zero if no version is present" do alternative_name = ab_test("link_color", "blue", "red") expect(experiment.version).to eq(0) expect(ab_user["link_color"]).to eq(alternative_name) end it "should save the version of the experiment to the session" do experiment.reset expect(experiment.version).to eq(1) alternative_name = ab_test("link_color", "blue", "red") expect(ab_user["link_color:1"]).to eq(alternative_name) end it "should load the experiment even if the version is not 0" do experiment.reset expect(experiment.version).to eq(1) alternative_name = ab_test("link_color", "blue", "red") expect(ab_user["link_color:1"]).to eq(alternative_name) return_alternative_name = ab_test("link_color", "blue", "red") expect(return_alternative_name).to eq(alternative_name) end it "should reset the session of a user on an older version of the experiment" do alternative_name = ab_test("link_color", "blue", "red") expect(ab_user["link_color"]).to eq(alternative_name) alternative = Split::Alternative.new(alternative_name, "link_color") expect(alternative.participant_count).to eq(1) experiment.reset expect(experiment.version).to eq(1) alternative = Split::Alternative.new(alternative_name, "link_color") expect(alternative.participant_count).to eq(0) new_alternative_name = ab_test("link_color", "blue", "red") expect(ab_user["link_color:1"]).to eq(new_alternative_name) new_alternative = Split::Alternative.new(new_alternative_name, "link_color") expect(new_alternative.participant_count).to eq(1) end it "should cleanup old versions of experiments from the session" do alternative_name = ab_test("link_color", "blue", "red") expect(ab_user["link_color"]).to eq(alternative_name) alternative = Split::Alternative.new(alternative_name, "link_color") expect(alternative.participant_count).to eq(1) experiment.reset expect(experiment.version).to eq(1) alternative = Split::Alternative.new(alternative_name, "link_color") expect(alternative.participant_count).to eq(0) new_alternative_name = ab_test("link_color", "blue", "red") expect(ab_user["link_color:1"]).to eq(new_alternative_name) end it "should only count completion of users on the current version" do alternative_name = ab_test("link_color", "blue", "red") expect(ab_user["link_color"]).to eq(alternative_name) Split::Alternative.new(alternative_name, "link_color") experiment.reset expect(experiment.version).to eq(1) ab_finished("link_color") alternative = Split::Alternative.new(alternative_name, "link_color") expect(alternative.completed_count).to eq(0) end end context "when redis is not available" do before(:each) do expect(Split).to receive(:redis).at_most(5).times.and_raise(Errno::ECONNREFUSED.new) end context "and db_failover config option is turned off" do before(:each) do Split.configure do |config| config.db_failover = false end end describe "ab_test" do it "should raise an exception" do expect { ab_test("link_color", "blue", "red") }.to raise_error(Errno::ECONNREFUSED) end end describe "finished" do it "should raise an exception" do expect { ab_finished("link_color") }.to raise_error(Errno::ECONNREFUSED) end end describe "disable split testing" do before(:each) do Split.configure do |config| config.enabled = false end end it "should not attempt to connect to redis" do expect { ab_test("link_color", "blue", "red") }.not_to raise_error end it "should return control variable" do expect(ab_test("link_color", "blue", "red")).to eq("blue") expect { ab_finished("link_color") }.not_to raise_error end end end context "and db_failover config option is turned on" do before(:each) do Split.configure do |config| config.db_failover = true end end describe "ab_test" do it "should not raise an exception" do expect { ab_test("link_color", "blue", "red") }.not_to raise_error end it "should call db_failover_on_db_error proc with error as parameter" do Split.configure do |config| config.db_failover_on_db_error = proc do |error| expect(error).to be_a(Errno::ECONNREFUSED) end end expect(Split.configuration.db_failover_on_db_error).to receive(:call).and_call_original ab_test("link_color", "blue", "red") end it "should always use first alternative" do expect(ab_test("link_color", "blue", "red")).to eq("blue") expect(ab_test("link_color", { "blue" => 0.01 }, "red" => 0.2)).to eq("blue") expect(ab_test("link_color", { "blue" => 0.8 }, { "red" => 20 })).to eq("blue") expect(ab_test("link_color", "blue", "red") do |alternative| "shared/#{alternative}" end).to eq("shared/blue") end context "and db_failover_allow_parameter_override config option is turned on" do before(:each) do Split.configure do |config| config.db_failover_allow_parameter_override = true end end context "and given an override parameter" do it "should use given override instead of the first alternative" do @params = { "ab_test" => { "link_color" => "red" } } expect(ab_test("link_color", "blue", "red")).to eq("red") expect(ab_test("link_color", "blue", "red", "green")).to eq("red") expect(ab_test("link_color", { "blue" => 0.01 }, "red" => 0.2)).to eq("red") expect(ab_test("link_color", { "blue" => 0.8 }, { "red" => 20 })).to eq("red") expect(ab_test("link_color", "blue", "red") do |alternative| "shared/#{alternative}" end).to eq("shared/red") end end end context "and preloaded config given" do before do Split.configuration.experiments[:link_color] = { alternatives: [ "blue", "red" ], } end it "uses first alternative" do expect(ab_test(:link_color)).to eq("blue") end end end describe "finished" do it "should not raise an exception" do expect { ab_finished("link_color") }.not_to raise_error end it "should call db_failover_on_db_error proc with error as parameter" do Split.configure do |config| config.db_failover_on_db_error = proc do |error| expect(error).to be_a(Errno::ECONNREFUSED) end end expect(Split.configuration.db_failover_on_db_error).to receive(:call).and_call_original ab_finished("link_color") end end end end context "with preloaded config" do before { Split.configuration.experiments = {} } it "pulls options from config file" do Split.configuration.experiments[:my_experiment] = { alternatives: [ "control_opt", "other_opt" ], goals: ["goal1", "goal2"] } ab_test :my_experiment expect(Split::Experiment.new(:my_experiment).alternatives.map(&:name)).to eq([ "control_opt", "other_opt" ]) expect(Split::Experiment.new(:my_experiment).goals).to eq([ "goal1", "goal2" ]) end it "can be called multiple times" do Split.configuration.experiments[:my_experiment] = { alternatives: [ "control_opt", "other_opt" ], goals: ["goal1", "goal2"] } 5.times { ab_test :my_experiment } experiment = Split::Experiment.new(:my_experiment) expect(experiment.alternatives.map(&:name)).to eq([ "control_opt", "other_opt" ]) expect(experiment.goals).to eq([ "goal1", "goal2" ]) expect(experiment.participant_count).to eq(1) end it "accepts multiple goals" do Split.configuration.experiments[:my_experiment] = { alternatives: [ "control_opt", "other_opt" ], goals: [ "goal1", "goal2", "goal3" ] } ab_test :my_experiment experiment = Split::Experiment.new(:my_experiment) expect(experiment.goals).to eq([ "goal1", "goal2", "goal3" ]) end it "allow specifying goals to be optional" do Split.configuration.experiments[:my_experiment] = { alternatives: [ "control_opt", "other_opt" ] } experiment = Split::Experiment.new(:my_experiment) expect(experiment.goals).to eq([]) end it "accepts multiple alternatives" do Split.configuration.experiments[:my_experiment] = { alternatives: [ "control_opt", "second_opt", "third_opt" ], } ab_test :my_experiment experiment = Split::Experiment.new(:my_experiment) expect(experiment.alternatives.map(&:name)).to eq([ "control_opt", "second_opt", "third_opt" ]) end it "accepts probability on alternatives" do Split.configuration.experiments[:my_experiment] = { alternatives: [ { name: "control_opt", percent: 67 }, { name: "second_opt", percent: 10 }, { name: "third_opt", percent: 23 }, ], } ab_test :my_experiment experiment = Split::Experiment.new(:my_experiment) expect(experiment.alternatives.collect { |a| [a.name, a.weight] }).to eq([["control_opt", 0.67], ["second_opt", 0.1], ["third_opt", 0.23]]) end it "accepts probability on some alternatives" do Split.configuration.experiments[:my_experiment] = { alternatives: [ { name: "control_opt", percent: 34 }, "second_opt", { name: "third_opt", percent: 23 }, "fourth_opt", ], } ab_test :my_experiment experiment = Split::Experiment.new(:my_experiment) names_and_weights = experiment.alternatives.collect { |a| [a.name, a.weight] } expect(names_and_weights).to eq([["control_opt", 0.34], ["second_opt", 0.215], ["third_opt", 0.23], ["fourth_opt", 0.215]]) expect(names_and_weights.inject(0) { |sum, nw| sum + nw[1] }).to eq(1.0) end it "allows name param without probability" do Split.configuration.experiments[:my_experiment] = { alternatives: [ { name: "control_opt" }, "second_opt", { name: "third_opt", percent: 64 }, ], } ab_test :my_experiment experiment = Split::Experiment.new(:my_experiment) names_and_weights = experiment.alternatives.collect { |a| [a.name, a.weight] } expect(names_and_weights).to eq([["control_opt", 0.18], ["second_opt", 0.18], ["third_opt", 0.64]]) expect(names_and_weights.inject(0) { |sum, nw| sum + nw[1] }).to eq(1.0) end it "fails gracefully if config is missing experiment" do Split.configuration.experiments = { other_experiment: { foo: "Bar" } } expect { ab_test :my_experiment }.to raise_error(Split::ExperimentNotFound) end it "fails gracefully if config is missing" do expect { Split.configuration.experiments = nil }.to raise_error(Split::InvalidExperimentsFormatError) end it "fails gracefully if config is missing alternatives" do Split.configuration.experiments[:my_experiment] = { foo: "Bar" } expect { ab_test :my_experiment }.to raise_error(NoMethodError) end end it "should handle multiple experiments correctly" do experiment2 = Split::ExperimentCatalog.find_or_create("link_color2", "blue", "red") ab_test("link_color", "blue", "red") ab_test("link_color2", "blue", "red") ab_finished("link_color2") experiment2.alternatives.each do |alt| expect(alt.unfinished_count).to eq(0) end end context "with goals" do before do @experiment = { "link_color" => ["purchase", "refund"] } @alternatives = ["blue", "red"] @experiment_name, @goals = normalize_metric(@experiment) @goal1 = @goals[0] @goal2 = @goals[1] end it "should normalize experiment" do expect(@experiment_name).to eq("link_color") expect(@goals).to eq(["purchase", "refund"]) end describe "ab_test" do it "should allow experiment goals interface as a single hash" do ab_test(@experiment, *@alternatives) experiment = Split::ExperimentCatalog.find("link_color") expect(experiment.goals).to eq(["purchase", "refund"]) end end describe "ab_finished" do before do @alternative_name = ab_test(@experiment, *@alternatives) end it "should increment the counter for the specified-goal completed alternative" do expect { ab_finished({ "link_color" => ["purchase"] }) } .to change { Split::Alternative.new(@alternative_name, @experiment_name).completed_count(@goal2) }.by(0) .and change { Split::Alternative.new(@alternative_name, @experiment_name).completed_count(@goal1) }.by(1) end end end end <MSG> Merge pull request #577 from gnanou/finish_inactive_experiment Handle correctly case when ab_finished is called before ab_test for a user <DFF> @@ -296,98 +296,126 @@ describe Split::Helper do end describe 'ab_finished' 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 + 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 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 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 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 experiment that the user is not participating in' do - ab_test('button_size', 'small', 'big') + 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(lambda { + ab_finished('button_size') + }).not_to change { Split::Alternative.new(a, 'button_size').completed_count } + end - # 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(lambda { - ab_finished('button_size') - }).not_to change { Split::Alternative.new('small', '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 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(lambda { - ab_finished('button_size') - }).not_to change { Split::Alternative.new(a, 'button_size').completed_count } - 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 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 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 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 versioned" do + @experiment.increment_version + @alternative_name = ab_test(@experiment_name, *@alternatives) - 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 + 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) + 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 - expect(ab_user[@experiment.key]).to eq(@alternative_name) - ab_finished(@experiment_name) - expect(ab_user.keys).to be_empty + 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 - it "should do nothing where the experiment was not started by this user" do - ab_user = nil - expect(lambda { ab_finished('some_experiment_not_started_by_the_user') }).not_to raise_exception + 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(lambda { + ab_finished('button_size') + }).not_to change { Split::Alternative.new('small', 'button_size').completed_count } + end 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) + 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 call the method without alternative" do - ab_user[@experiment.key] = nil - expect(self).not_to receive(:some_method) - ab_finished(@experiment_name) + 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
103
Merge pull request #577 from gnanou/finish_inactive_experiment
75
.rb
rb
mit
splitrb/split
10072081
<NME> helper_spec.rb <BEF> # frozen_string_literal: true require "spec_helper" # TODO change some of these tests to use Rack::Test describe Split::Helper do include Split::Helper let(:experiment) { Split::ExperimentCatalog.find_or_create("link_color", "blue", "red") } describe "ab_test" do it "should not raise an error when passed strings for alternatives" do expect { ab_test("xyz", "1", "2", "3") }.not_to raise_error end it "should not raise an error when passed an array for alternatives" do expect { ab_test("xyz", ["1", "2", "3"]) }.not_to raise_error end it "should raise the appropriate error when passed integers for alternatives" do expect { ab_test("xyz", 1, 2, 3) }.to raise_error(ArgumentError) end it "should raise the appropriate error when passed symbols for alternatives" do expect { ab_test("xyz", :a, :b, :c) }.to raise_error(ArgumentError) end it "should not raise error when passed an array for goals" do expect { ab_test({ "link_color" => ["purchase", "refund"] }, "blue", "red") }.not_to raise_error end it "should not raise error when passed just one goal" do expect { ab_test({ "link_color" => "purchase" }, "blue", "red") }.not_to raise_error end it "raises an appropriate error when processing combined expirements" do Split.configuration.experiments = { combined_exp_1: { alternatives: [ { name: "control", percent: 50 }, { name: "test-alt", percent: 50 } ], metric: :my_metric, combined_experiments: [:combined_exp_1_sub_1] } } Split::ExperimentCatalog.find_or_create("combined_exp_1") expect { ab_test("combined_exp_1") }.to raise_error(Split::InvalidExperimentsFormatError) end it "should assign a random alternative to a new user when there are an equal number of alternatives assigned" do ab_test("link_color", "blue", "red") expect(["red", "blue"]).to include(ab_user["link_color"]) end it "should increment the participation counter after assignment to a new user" do previous_red_count = Split::Alternative.new("red", "link_color").participant_count previous_blue_count = Split::Alternative.new("blue", "link_color").participant_count ab_test("link_color", "blue", "red") new_red_count = Split::Alternative.new("red", "link_color").participant_count new_blue_count = Split::Alternative.new("blue", "link_color").participant_count expect((new_red_count + new_blue_count)).to eq(previous_red_count + previous_blue_count + 1) end it "should not increment the counter for an experiment that the user is not participating in" do ab_test("link_color", "blue", "red") e = Split::ExperimentCatalog.find_or_create("button_size", "small", "big") expect { # User shouldn't participate in this second experiment ab_test("button_size", "small", "big") }.not_to change { e.participant_count } end it "should not increment the counter for an ended experiment" do e = Split::ExperimentCatalog.find_or_create("button_size", "small", "big") e.winner = "small" expect { a = ab_test("button_size", "small", "big") expect(a).to eq("small") }.not_to change { e.participant_count } end it "should not increment the counter for an not started experiment" do expect(Split.configuration).to receive(:start_manually).and_return(true) e = Split::ExperimentCatalog.find_or_create("button_size", "small", "big") expect { a = ab_test("button_size", "small", "big") expect(a).to eq("small") }.not_to change { e.participant_count } end it "should return the given alternative for an existing user" do expect(ab_test("link_color", "blue", "red")).to eq ab_test("link_color", "blue", "red") end it "should always return the winner if one is present" do experiment.winner = "orange" expect(ab_test("link_color", "blue", "red")).to eq("orange") end it "should allow the alternative to be forced by passing it in the params" do # ?ab_test[link_color]=blue @params = { "ab_test" => { "link_color" => "blue" } } alternative = ab_test("link_color", "blue", "red") expect(alternative).to eq("blue") alternative = ab_test("link_color", { "blue" => 1 }, "red" => 5) expect(alternative).to eq("blue") @params = { "ab_test" => { "link_color" => "red" } } alternative = ab_test("link_color", "blue", "red") expect(alternative).to eq("red") alternative = ab_test("link_color", { "blue" => 5 }, "red" => 1) expect(alternative).to eq("red") end it "should not allow an arbitrary alternative" do @params = { "ab_test" => { "link_color" => "pink" } } alternative = ab_test("link_color", "blue") expect(alternative).to eq("blue") end it "should not store the split when a param forced alternative" do @params = { "ab_test" => { "link_color" => "blue" } } expect(ab_user).not_to receive(:[]=) ab_test("link_color", "blue", "red") end it "SPLIT_DISABLE query parameter should also force the alternative (uses control)" do @params = { "SPLIT_DISABLE" => "true" } alternative = ab_test("link_color", "blue", "red") expect(alternative).to eq("blue") alternative = ab_test("link_color", { "blue" => 1 }, "red" => 5) expect(alternative).to eq("blue") alternative = ab_test("link_color", "red", "blue") expect(alternative).to eq("red") alternative = ab_test("link_color", { "red" => 5 }, "blue" => 1) expect(alternative).to eq("red") end it "should not store the split when Split generically disabled" do @params = { "SPLIT_DISABLE" => "true" } expect(ab_user).not_to receive(:[]=) ab_test("link_color", "blue", "red") end context "when store_override is set" do before { Split.configuration.store_override = true } it "should store the forced alternative" do @params = { "ab_test" => { "link_color" => "blue" } } expect(ab_user).to receive(:[]=).with("link_color", "blue") ab_test("link_color", "blue", "red") end end context "when on_trial_choose is set" do before { Split.configuration.on_trial_choose = :some_method } it "should call the method" do expect(self).to receive(:some_method) ab_test("link_color", "blue", "red") end end it "should allow passing a block" do alt = ab_test("link_color", "blue", "red") ret = ab_test("link_color", "blue", "red") { |alternative| "shared/#{alternative}" } expect(ret).to eq("shared/#{alt}") end it "should allow the share of visitors see an alternative to be specified" do ab_test("link_color", { "blue" => 0.8 }, { "red" => 20 }) expect(["red", "blue"]).to include(ab_user["link_color"]) end it "should allow alternative weighting interface as a single hash" do ab_test("link_color", { "blue" => 0.01 }, "red" => 0.2) experiment = Split::ExperimentCatalog.find("link_color") expect(experiment.alternatives.map(&:name)).to eq(["blue", "red"]) expect(experiment.alternatives.collect { |a| a.weight }).to match_array([0.01, 0.2]) end it "should only let a user participate in one experiment at a time" do link_color = ab_test("link_color", "blue", "red") ab_test("button_size", "small", "big") expect(ab_user["link_color"]).to eq(link_color) big = Split::Alternative.new("big", "button_size") expect(big.participant_count).to eq(0) small = Split::Alternative.new("small", "button_size") expect(small.participant_count).to eq(0) end it "should let a user participate in many experiment with allow_multiple_experiments option" do Split.configure do |config| config.allow_multiple_experiments = true end link_color = ab_test("link_color", "blue", "red") button_size = ab_test("button_size", "small", "big") expect(ab_user["link_color"]).to eq(link_color) expect(ab_user["button_size"]).to eq(button_size) button_size_alt = Split::Alternative.new(button_size, "button_size") expect(button_size_alt.participant_count).to eq(1) end context "with allow_multiple_experiments = 'control'" do it "should let a user participate in many experiment with one non-'control' alternative" do Split.configure do |config| config.allow_multiple_experiments = "control" end groups = 100.times.map do |n| ab_test("test#{n}".to_sym, { "control" => (100 - n) }, { "test#{n}-alt" => n }) end experiments = ab_user.active_experiments expect(experiments.size).to be > 1 count_control = experiments.values.count { |g| g == "control" } expect(count_control).to eq(experiments.size - 1) count_alts = groups.count { |g| g != "control" } expect(count_alts).to eq(1) end context "when user already has experiment" do let(:mock_user) { Split::User.new(self, { "test_0" => "test-alt" }) } before do Split.configure do |config| config.allow_multiple_experiments = "control" end Split::ExperimentCatalog.find_or_initialize("test_0", "control", "test-alt").save Split::ExperimentCatalog.find_or_initialize("test_1", "control", "test-alt").save end it "should restore previously selected alternative" do expect(ab_user.active_experiments.size).to eq 1 expect(ab_test(:test_0, { "control" => 100 }, { "test-alt" => 1 })).to eq "test-alt" expect(ab_test(:test_0, { "control" => 1 }, { "test-alt" => 100 })).to eq "test-alt" end it "should select the correct alternatives after experiment resets" do experiment = Split::ExperimentCatalog.find(:test_0) experiment.reset mock_user[experiment.key] = "test-alt" expect(ab_user.active_experiments.size).to eq 1 expect(ab_test(:test_0, { "control" => 100 }, { "test-alt" => 1 })).to eq "test-alt" expect(ab_test(:test_0, { "control" => 0 }, { "test-alt" => 100 })).to eq "test-alt" end it "lets override existing choice" do pending "this requires user store reset on first call not depending on whelther it is current trial" @params = { "ab_test" => { "test_1" => "test-alt" } } expect(ab_test(:test_0, { "control" => 0 }, { "test-alt" => 100 })).to eq "control" expect(ab_test(:test_1, { "control" => 100 }, { "test-alt" => 1 })).to eq "test-alt" end end end it "should not over-write a finished key when an experiment is on a later version" do experiment.increment_version ab_user = { experiment.key => "blue", experiment.finished_key => true } finished_session = ab_user.dup ab_test("link_color", "blue", "red") expect(ab_user).to eq(finished_session) end end describe "metadata" do context "is defined" do before do Split.configuration.experiments = { my_experiment: { alternatives: ["one", "two"], resettable: false, metadata: { "one" => "Meta1", "two" => "Meta2" } } } end it "should be passed to helper block" do @params = { "ab_test" => { "my_experiment" => "two" } } expect(ab_test("my_experiment")).to eq "two" expect(ab_test("my_experiment") do |alternative, meta| meta end).to eq("Meta2") end describe 'ab_finished' 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 experiment that the user is not participating in' do ab_test('button_size', 'small', 'big') # 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(lambda { ab_finished('button_size') }).not_to change { Split::Alternative.new('small', 'button_size').completed_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' a = ab_test('button_size', 'small', 'big') expect(a).to eq('small') expect(lambda { 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 it "should do nothing where the experiment was not started by this user" do ab_user = nil expect(lambda { ab_finished('some_experiment_not_started_by_the_user') }).not_to raise_exception 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 alternative = ab_test("link_color", "blue", "red") expect(Split::Alternative.new(alternative, "link_color").participant_count).to eq(1) alternative = ab_test("button_size", "small", "big") expect(Split::Alternative.new(alternative, "button_size").participant_count).to eq(0) end it "should not increment the completed counter" do # So, user should be participating in the link_color experiment and # receive the control for button_size. As the user is not participating in # the button size experiment, finishing it should not increase the # completion count for that alternative. expect { ab_finished("button_size") }.not_to change { Split::Alternative.new("small", "button_size").completed_count } end end context "for an experiment that the user does not participate in" do before do Split::ExperimentCatalog.find_or_create(:not_started_experiment, "control", "alt") end it "should not raise an exception" do expect { ab_finished(:not_started_experiment) }.not_to raise_exception end it "should not change the user state when reset is false" do expect { ab_finished(:not_started_experiment, reset: false) }.not_to change { ab_user.keys }.from([]) end it "should not change the user state when reset is true" do expect(self).not_to receive(:reset!) ab_finished(:not_started_experiment) end it "should not increment the completed counter" do ab_finished(:not_started_experiment) expect(Split::Alternative.new("control", :not_started_experiment).completed_count).to eq(0) expect(Split::Alternative.new("alt", :not_started_experiment).completed_count).to eq(0) end end end context "finished with config" do it "passes reset option" do Split.configuration.experiments = { my_experiment: { alternatives: ["one", "two"], resettable: false, } } alternative = ab_test(:my_experiment) experiment = Split::ExperimentCatalog.find :my_experiment ab_finished :my_experiment expect(ab_user[experiment.key]).to eq(alternative) expect(ab_user[experiment.finished_key]).to eq(true) end end context "finished with metric name" do before { Split.configuration.experiments = {} } before { expect(Split::Alternative).to receive(:new).at_least(1).times.and_call_original } def should_finish_experiment(experiment_name, should_finish = true) alts = Split.configuration.experiments[experiment_name][:alternatives] experiment = Split::ExperimentCatalog.find_or_create(experiment_name, *alts) alt_name = ab_user[experiment.key] = alts.first alt = double("alternative") expect(alt).to receive(:name).at_most(1).times.and_return(alt_name) expect(Split::Alternative).to receive(:new).at_most(1).times.with(alt_name, experiment_name.to_s).and_return(alt) if should_finish expect(alt).to receive(:increment_completion).at_most(1).times else expect(alt).not_to receive(:increment_completion) end end it "completes the test" do Split.configuration.experiments[:my_experiment] = { alternatives: [ "control_opt", "other_opt" ], metric: :my_metric } should_finish_experiment :my_experiment ab_finished :my_metric end it "completes all relevant tests" do Split.configuration.experiments = { exp_1: { alternatives: [ "1-1", "1-2" ], metric: :my_metric }, exp_2: { alternatives: [ "2-1", "2-2" ], metric: :another_metric }, exp_3: { alternatives: [ "3-1", "3-2" ], metric: :my_metric }, } should_finish_experiment :exp_1 should_finish_experiment :exp_2, false should_finish_experiment :exp_3 ab_finished :my_metric end it "passes reset option" do Split.configuration.experiments = { my_exp: { alternatives: ["one", "two"], metric: :my_metric, resettable: false, } } alternative_name = ab_test(:my_exp) exp = Split::ExperimentCatalog.find :my_exp ab_finished :my_metric expect(ab_user[exp.key]).to eq(alternative_name) expect(ab_user[exp.finished_key]).to be_truthy end it "passes through options" do Split.configuration.experiments = { my_exp: { alternatives: ["one", "two"], metric: :my_metric, } } alternative_name = ab_test(:my_exp) exp = Split::ExperimentCatalog.find :my_exp ab_finished :my_metric, reset: false expect(ab_user[exp.key]).to eq(alternative_name) expect(ab_user[exp.finished_key]).to be_truthy end end describe "conversions" do it "should return a conversion rate for an alternative" do alternative_name = ab_test("link_color", "blue", "red") previous_convertion_rate = Split::Alternative.new(alternative_name, "link_color").conversion_rate expect(previous_convertion_rate).to eq(0.0) ab_finished("link_color") new_convertion_rate = Split::Alternative.new(alternative_name, "link_color").conversion_rate expect(new_convertion_rate).to eq(1.0) end end describe "active experiments" do it "should show an active test" do alternative = ab_test("def", "4", "5", "6") expect(active_experiments.count).to eq 1 expect(active_experiments.first[0]).to eq "def" expect(active_experiments.first[1]).to eq alternative end it "should show a finished test" do alternative = ab_test("def", "4", "5", "6") ab_finished("def", { reset: false }) expect(active_experiments.count).to eq 1 expect(active_experiments.first[0]).to eq "def" expect(active_experiments.first[1]).to eq alternative end it "should show an active test when an experiment is on a later version" do experiment.reset expect(experiment.version).to eq(1) ab_test("link_color", "blue", "red") expect(active_experiments.count).to eq 1 expect(active_experiments.first[0]).to eq "link_color" end it "should show versioned tests properly" do 10.times { experiment.reset } alternative = ab_test(experiment.name, "blue", "red") ab_finished(experiment.name, reset: false) expect(experiment.version).to eq(10) expect(active_experiments.count).to eq 1 expect(active_experiments).to eq({ "link_color" => alternative }) end it "should show multiple tests" do Split.configure do |config| config.allow_multiple_experiments = true end alternative = ab_test("def", "4", "5", "6") another_alternative = ab_test("ghi", "7", "8", "9") expect(active_experiments.count).to eq 2 expect(active_experiments["def"]).to eq alternative expect(active_experiments["ghi"]).to eq another_alternative end it "should not show tests with winners" do Split.configure do |config| config.allow_multiple_experiments = true end e = Split::ExperimentCatalog.find_or_create("def", "4", "5", "6") e.winner = "4" ab_test("def", "4", "5", "6") another_alternative = ab_test("ghi", "7", "8", "9") expect(active_experiments.count).to eq 1 expect(active_experiments.first[0]).to eq "ghi" expect(active_experiments.first[1]).to eq another_alternative end end describe "when user is a robot" do before(:each) do @request = OpenStruct.new(user_agent: "Googlebot/2.1 (+http://www.google.com/bot.html)") end describe "ab_test" do it "should return the control" do alternative = ab_test("link_color", "blue", "red") expect(alternative).to eq experiment.control.name end it "should not create a experiment" do ab_test("link_color", "blue", "red") expect(Split::Experiment.new("link_color")).to be_a_new_record end it "should not increment the participation count" do previous_red_count = Split::Alternative.new("red", "link_color").participant_count previous_blue_count = Split::Alternative.new("blue", "link_color").participant_count ab_test("link_color", "blue", "red") new_red_count = Split::Alternative.new("red", "link_color").participant_count new_blue_count = Split::Alternative.new("blue", "link_color").participant_count expect((new_red_count + new_blue_count)).to eq(previous_red_count + previous_blue_count) end end describe "finished" do it "should not increment the completed count" do alternative_name = ab_test("link_color", "blue", "red") previous_completion_count = Split::Alternative.new(alternative_name, "link_color").completed_count ab_finished("link_color") new_completion_count = Split::Alternative.new(alternative_name, "link_color").completed_count expect(new_completion_count).to eq(previous_completion_count) end end end describe "when providing custom ignore logic" do context "using a proc to configure custom logic" do before(:each) do Split.configure do |c| c.ignore_filter = proc { |request| true } # ignore everything end end it "ignores the ab_test" do ab_test("link_color", "blue", "red") red_count = Split::Alternative.new("red", "link_color").participant_count blue_count = Split::Alternative.new("blue", "link_color").participant_count expect((red_count + blue_count)).to be(0) end end end shared_examples_for "a disabled test" do describe "ab_test" do it "should return the control" do alternative = ab_test("link_color", "blue", "red") expect(alternative).to eq experiment.control.name end it "should not increment the participation count" do previous_red_count = Split::Alternative.new("red", "link_color").participant_count previous_blue_count = Split::Alternative.new("blue", "link_color").participant_count ab_test("link_color", "blue", "red") new_red_count = Split::Alternative.new("red", "link_color").participant_count new_blue_count = Split::Alternative.new("blue", "link_color").participant_count expect((new_red_count + new_blue_count)).to eq(previous_red_count + previous_blue_count) end end describe "finished" do it "should not increment the completed count" do alternative_name = ab_test("link_color", "blue", "red") previous_completion_count = Split::Alternative.new(alternative_name, "link_color").completed_count ab_finished("link_color") new_completion_count = Split::Alternative.new(alternative_name, "link_color").completed_count expect(new_completion_count).to eq(previous_completion_count) end end end describe "when ip address is ignored" do context "individually" do before(:each) do @request = OpenStruct.new(ip: "81.19.48.130") Split.configure do |c| c.ignore_ip_addresses << "81.19.48.130" end end it_behaves_like "a disabled test" end context "for a range" do before(:each) do @request = OpenStruct.new(ip: "81.19.48.129") Split.configure do |c| c.ignore_ip_addresses << /81\.19\.48\.[0-9]+/ end end it_behaves_like "a disabled test" end context "using both a range and a specific value" do before(:each) do @request = OpenStruct.new(ip: "81.19.48.128") Split.configure do |c| c.ignore_ip_addresses << "81.19.48.130" c.ignore_ip_addresses << /81\.19\.48\.[0-9]+/ end end it_behaves_like "a disabled test" end context "when ignored other address" do before do @request = OpenStruct.new(ip: "1.1.1.1") Split.configure do |c| c.ignore_ip_addresses << "81.19.48.130" end end it "works as usual" do alternative_name = ab_test("link_color", "red", "blue") expect { ab_finished("link_color") }.to change(Split::Alternative.new(alternative_name, "link_color"), :completed_count).by(1) end end end describe "when user is previewing" do before(:each) do @request = OpenStruct.new(headers: { "x-purpose" => "preview" }) end it_behaves_like "a disabled test" end describe "versioned experiments" do it "should use version zero if no version is present" do alternative_name = ab_test("link_color", "blue", "red") expect(experiment.version).to eq(0) expect(ab_user["link_color"]).to eq(alternative_name) end it "should save the version of the experiment to the session" do experiment.reset expect(experiment.version).to eq(1) alternative_name = ab_test("link_color", "blue", "red") expect(ab_user["link_color:1"]).to eq(alternative_name) end it "should load the experiment even if the version is not 0" do experiment.reset expect(experiment.version).to eq(1) alternative_name = ab_test("link_color", "blue", "red") expect(ab_user["link_color:1"]).to eq(alternative_name) return_alternative_name = ab_test("link_color", "blue", "red") expect(return_alternative_name).to eq(alternative_name) end it "should reset the session of a user on an older version of the experiment" do alternative_name = ab_test("link_color", "blue", "red") expect(ab_user["link_color"]).to eq(alternative_name) alternative = Split::Alternative.new(alternative_name, "link_color") expect(alternative.participant_count).to eq(1) experiment.reset expect(experiment.version).to eq(1) alternative = Split::Alternative.new(alternative_name, "link_color") expect(alternative.participant_count).to eq(0) new_alternative_name = ab_test("link_color", "blue", "red") expect(ab_user["link_color:1"]).to eq(new_alternative_name) new_alternative = Split::Alternative.new(new_alternative_name, "link_color") expect(new_alternative.participant_count).to eq(1) end it "should cleanup old versions of experiments from the session" do alternative_name = ab_test("link_color", "blue", "red") expect(ab_user["link_color"]).to eq(alternative_name) alternative = Split::Alternative.new(alternative_name, "link_color") expect(alternative.participant_count).to eq(1) experiment.reset expect(experiment.version).to eq(1) alternative = Split::Alternative.new(alternative_name, "link_color") expect(alternative.participant_count).to eq(0) new_alternative_name = ab_test("link_color", "blue", "red") expect(ab_user["link_color:1"]).to eq(new_alternative_name) end it "should only count completion of users on the current version" do alternative_name = ab_test("link_color", "blue", "red") expect(ab_user["link_color"]).to eq(alternative_name) Split::Alternative.new(alternative_name, "link_color") experiment.reset expect(experiment.version).to eq(1) ab_finished("link_color") alternative = Split::Alternative.new(alternative_name, "link_color") expect(alternative.completed_count).to eq(0) end end context "when redis is not available" do before(:each) do expect(Split).to receive(:redis).at_most(5).times.and_raise(Errno::ECONNREFUSED.new) end context "and db_failover config option is turned off" do before(:each) do Split.configure do |config| config.db_failover = false end end describe "ab_test" do it "should raise an exception" do expect { ab_test("link_color", "blue", "red") }.to raise_error(Errno::ECONNREFUSED) end end describe "finished" do it "should raise an exception" do expect { ab_finished("link_color") }.to raise_error(Errno::ECONNREFUSED) end end describe "disable split testing" do before(:each) do Split.configure do |config| config.enabled = false end end it "should not attempt to connect to redis" do expect { ab_test("link_color", "blue", "red") }.not_to raise_error end it "should return control variable" do expect(ab_test("link_color", "blue", "red")).to eq("blue") expect { ab_finished("link_color") }.not_to raise_error end end end context "and db_failover config option is turned on" do before(:each) do Split.configure do |config| config.db_failover = true end end describe "ab_test" do it "should not raise an exception" do expect { ab_test("link_color", "blue", "red") }.not_to raise_error end it "should call db_failover_on_db_error proc with error as parameter" do Split.configure do |config| config.db_failover_on_db_error = proc do |error| expect(error).to be_a(Errno::ECONNREFUSED) end end expect(Split.configuration.db_failover_on_db_error).to receive(:call).and_call_original ab_test("link_color", "blue", "red") end it "should always use first alternative" do expect(ab_test("link_color", "blue", "red")).to eq("blue") expect(ab_test("link_color", { "blue" => 0.01 }, "red" => 0.2)).to eq("blue") expect(ab_test("link_color", { "blue" => 0.8 }, { "red" => 20 })).to eq("blue") expect(ab_test("link_color", "blue", "red") do |alternative| "shared/#{alternative}" end).to eq("shared/blue") end context "and db_failover_allow_parameter_override config option is turned on" do before(:each) do Split.configure do |config| config.db_failover_allow_parameter_override = true end end context "and given an override parameter" do it "should use given override instead of the first alternative" do @params = { "ab_test" => { "link_color" => "red" } } expect(ab_test("link_color", "blue", "red")).to eq("red") expect(ab_test("link_color", "blue", "red", "green")).to eq("red") expect(ab_test("link_color", { "blue" => 0.01 }, "red" => 0.2)).to eq("red") expect(ab_test("link_color", { "blue" => 0.8 }, { "red" => 20 })).to eq("red") expect(ab_test("link_color", "blue", "red") do |alternative| "shared/#{alternative}" end).to eq("shared/red") end end end context "and preloaded config given" do before do Split.configuration.experiments[:link_color] = { alternatives: [ "blue", "red" ], } end it "uses first alternative" do expect(ab_test(:link_color)).to eq("blue") end end end describe "finished" do it "should not raise an exception" do expect { ab_finished("link_color") }.not_to raise_error end it "should call db_failover_on_db_error proc with error as parameter" do Split.configure do |config| config.db_failover_on_db_error = proc do |error| expect(error).to be_a(Errno::ECONNREFUSED) end end expect(Split.configuration.db_failover_on_db_error).to receive(:call).and_call_original ab_finished("link_color") end end end end context "with preloaded config" do before { Split.configuration.experiments = {} } it "pulls options from config file" do Split.configuration.experiments[:my_experiment] = { alternatives: [ "control_opt", "other_opt" ], goals: ["goal1", "goal2"] } ab_test :my_experiment expect(Split::Experiment.new(:my_experiment).alternatives.map(&:name)).to eq([ "control_opt", "other_opt" ]) expect(Split::Experiment.new(:my_experiment).goals).to eq([ "goal1", "goal2" ]) end it "can be called multiple times" do Split.configuration.experiments[:my_experiment] = { alternatives: [ "control_opt", "other_opt" ], goals: ["goal1", "goal2"] } 5.times { ab_test :my_experiment } experiment = Split::Experiment.new(:my_experiment) expect(experiment.alternatives.map(&:name)).to eq([ "control_opt", "other_opt" ]) expect(experiment.goals).to eq([ "goal1", "goal2" ]) expect(experiment.participant_count).to eq(1) end it "accepts multiple goals" do Split.configuration.experiments[:my_experiment] = { alternatives: [ "control_opt", "other_opt" ], goals: [ "goal1", "goal2", "goal3" ] } ab_test :my_experiment experiment = Split::Experiment.new(:my_experiment) expect(experiment.goals).to eq([ "goal1", "goal2", "goal3" ]) end it "allow specifying goals to be optional" do Split.configuration.experiments[:my_experiment] = { alternatives: [ "control_opt", "other_opt" ] } experiment = Split::Experiment.new(:my_experiment) expect(experiment.goals).to eq([]) end it "accepts multiple alternatives" do Split.configuration.experiments[:my_experiment] = { alternatives: [ "control_opt", "second_opt", "third_opt" ], } ab_test :my_experiment experiment = Split::Experiment.new(:my_experiment) expect(experiment.alternatives.map(&:name)).to eq([ "control_opt", "second_opt", "third_opt" ]) end it "accepts probability on alternatives" do Split.configuration.experiments[:my_experiment] = { alternatives: [ { name: "control_opt", percent: 67 }, { name: "second_opt", percent: 10 }, { name: "third_opt", percent: 23 }, ], } ab_test :my_experiment experiment = Split::Experiment.new(:my_experiment) expect(experiment.alternatives.collect { |a| [a.name, a.weight] }).to eq([["control_opt", 0.67], ["second_opt", 0.1], ["third_opt", 0.23]]) end it "accepts probability on some alternatives" do Split.configuration.experiments[:my_experiment] = { alternatives: [ { name: "control_opt", percent: 34 }, "second_opt", { name: "third_opt", percent: 23 }, "fourth_opt", ], } ab_test :my_experiment experiment = Split::Experiment.new(:my_experiment) names_and_weights = experiment.alternatives.collect { |a| [a.name, a.weight] } expect(names_and_weights).to eq([["control_opt", 0.34], ["second_opt", 0.215], ["third_opt", 0.23], ["fourth_opt", 0.215]]) expect(names_and_weights.inject(0) { |sum, nw| sum + nw[1] }).to eq(1.0) end it "allows name param without probability" do Split.configuration.experiments[:my_experiment] = { alternatives: [ { name: "control_opt" }, "second_opt", { name: "third_opt", percent: 64 }, ], } ab_test :my_experiment experiment = Split::Experiment.new(:my_experiment) names_and_weights = experiment.alternatives.collect { |a| [a.name, a.weight] } expect(names_and_weights).to eq([["control_opt", 0.18], ["second_opt", 0.18], ["third_opt", 0.64]]) expect(names_and_weights.inject(0) { |sum, nw| sum + nw[1] }).to eq(1.0) end it "fails gracefully if config is missing experiment" do Split.configuration.experiments = { other_experiment: { foo: "Bar" } } expect { ab_test :my_experiment }.to raise_error(Split::ExperimentNotFound) end it "fails gracefully if config is missing" do expect { Split.configuration.experiments = nil }.to raise_error(Split::InvalidExperimentsFormatError) end it "fails gracefully if config is missing alternatives" do Split.configuration.experiments[:my_experiment] = { foo: "Bar" } expect { ab_test :my_experiment }.to raise_error(NoMethodError) end end it "should handle multiple experiments correctly" do experiment2 = Split::ExperimentCatalog.find_or_create("link_color2", "blue", "red") ab_test("link_color", "blue", "red") ab_test("link_color2", "blue", "red") ab_finished("link_color2") experiment2.alternatives.each do |alt| expect(alt.unfinished_count).to eq(0) end end context "with goals" do before do @experiment = { "link_color" => ["purchase", "refund"] } @alternatives = ["blue", "red"] @experiment_name, @goals = normalize_metric(@experiment) @goal1 = @goals[0] @goal2 = @goals[1] end it "should normalize experiment" do expect(@experiment_name).to eq("link_color") expect(@goals).to eq(["purchase", "refund"]) end describe "ab_test" do it "should allow experiment goals interface as a single hash" do ab_test(@experiment, *@alternatives) experiment = Split::ExperimentCatalog.find("link_color") expect(experiment.goals).to eq(["purchase", "refund"]) end end describe "ab_finished" do before do @alternative_name = ab_test(@experiment, *@alternatives) end it "should increment the counter for the specified-goal completed alternative" do expect { ab_finished({ "link_color" => ["purchase"] }) } .to change { Split::Alternative.new(@alternative_name, @experiment_name).completed_count(@goal2) }.by(0) .and change { Split::Alternative.new(@alternative_name, @experiment_name).completed_count(@goal1) }.by(1) end end end end <MSG> Merge pull request #577 from gnanou/finish_inactive_experiment Handle correctly case when ab_finished is called before ab_test for a user <DFF> @@ -296,98 +296,126 @@ describe Split::Helper do end describe 'ab_finished' 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 + 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 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 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 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 experiment that the user is not participating in' do - ab_test('button_size', 'small', 'big') + 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(lambda { + ab_finished('button_size') + }).not_to change { Split::Alternative.new(a, 'button_size').completed_count } + end - # 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(lambda { - ab_finished('button_size') - }).not_to change { Split::Alternative.new('small', '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 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(lambda { - ab_finished('button_size') - }).not_to change { Split::Alternative.new(a, 'button_size').completed_count } - 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 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 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 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 versioned" do + @experiment.increment_version + @alternative_name = ab_test(@experiment_name, *@alternatives) - 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 + 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) + 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 - expect(ab_user[@experiment.key]).to eq(@alternative_name) - ab_finished(@experiment_name) - expect(ab_user.keys).to be_empty + 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 - it "should do nothing where the experiment was not started by this user" do - ab_user = nil - expect(lambda { ab_finished('some_experiment_not_started_by_the_user') }).not_to raise_exception + 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(lambda { + ab_finished('button_size') + }).not_to change { Split::Alternative.new('small', 'button_size').completed_count } + end 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) + 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 call the method without alternative" do - ab_user[@experiment.key] = nil - expect(self).not_to receive(:some_method) - ab_finished(@experiment_name) + 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
103
Merge pull request #577 from gnanou/finish_inactive_experiment
75
.rb
rb
mit
splitrb/split
10072082
<NME> helpers.rb <BEF> # frozen_string_literal: true module Split module DashboardHelpers def h(text) Rack::Utils.escape_html(text) end def url(*path_parts) [ path_prefix, path_parts ].join("/").squeeze("/") end def path_prefix request.env["SCRIPT_NAME"] end def number_to_percentage(number, precision = 2) round(number * 100) def round(number, precision = 2) begin BigDecimal.new(number.to_s) rescue ArgumentError BigDecimal.new(0) end.round(precision).to_f end def confidence_level(z_score) return z_score if z_score.is_a? String z = round(z_score.to_s.to_f, 3).abs if z >= 2.58 "99% confidence" elsif z >= 1.96 "95% confidence" elsif z >= 1.65 "90% confidence" else "Insufficient confidence" end end end end <MSG> Fix Bigdecimal warnings * replace BigDecimal.new() with BigDecimal() <DFF> @@ -19,9 +19,9 @@ module Split def round(number, precision = 2) begin - BigDecimal.new(number.to_s) + BigDecimal(number.to_s) rescue ArgumentError - BigDecimal.new(0) + BigDecimal(0) end.round(precision).to_f end
2
Fix Bigdecimal warnings
2
.rb
rb
mit
splitrb/split
10072083
<NME> helpers.rb <BEF> # frozen_string_literal: true module Split module DashboardHelpers def h(text) Rack::Utils.escape_html(text) end def url(*path_parts) [ path_prefix, path_parts ].join("/").squeeze("/") end def path_prefix request.env["SCRIPT_NAME"] end def number_to_percentage(number, precision = 2) round(number * 100) def round(number, precision = 2) begin BigDecimal.new(number.to_s) rescue ArgumentError BigDecimal.new(0) end.round(precision).to_f end def confidence_level(z_score) return z_score if z_score.is_a? String z = round(z_score.to_s.to_f, 3).abs if z >= 2.58 "99% confidence" elsif z >= 1.96 "95% confidence" elsif z >= 1.65 "90% confidence" else "Insufficient confidence" end end end end <MSG> Fix Bigdecimal warnings * replace BigDecimal.new() with BigDecimal() <DFF> @@ -19,9 +19,9 @@ module Split def round(number, precision = 2) begin - BigDecimal.new(number.to_s) + BigDecimal(number.to_s) rescue ArgumentError - BigDecimal.new(0) + BigDecimal(0) end.round(precision).to_f end
2
Fix Bigdecimal warnings
2
.rb
rb
mit
splitrb/split
10072084
<NME> helpers.rb <BEF> # frozen_string_literal: true module Split module DashboardHelpers def h(text) Rack::Utils.escape_html(text) end def url(*path_parts) [ path_prefix, path_parts ].join("/").squeeze("/") end def path_prefix request.env["SCRIPT_NAME"] end def number_to_percentage(number, precision = 2) round(number * 100) def round(number, precision = 2) begin BigDecimal.new(number.to_s) rescue ArgumentError BigDecimal.new(0) end.round(precision).to_f end def confidence_level(z_score) return z_score if z_score.is_a? String z = round(z_score.to_s.to_f, 3).abs if z >= 2.58 "99% confidence" elsif z >= 1.96 "95% confidence" elsif z >= 1.65 "90% confidence" else "Insufficient confidence" end end end end <MSG> Fix Bigdecimal warnings * replace BigDecimal.new() with BigDecimal() <DFF> @@ -19,9 +19,9 @@ module Split def round(number, precision = 2) begin - BigDecimal.new(number.to_s) + BigDecimal(number.to_s) rescue ArgumentError - BigDecimal.new(0) + BigDecimal(0) end.round(precision).to_f end
2
Fix Bigdecimal warnings
2
.rb
rb
mit
splitrb/split
10072085
<NME> README.md <BEF> # Emmet — the essential toolkit for web-developers Emmet is a web-developer’s toolkit for boosting HTML & CSS code writing. With Emmet, you can type expressions (_abbreviations_) similar to CSS selectors and convert them into code fragment with a single keystroke. For example, this abbreviation: ``` ul#nav>li.item$*4>a{Item $} ``` ...can be expanded into: ```html <ul id="nav"> <li class="item1"><a href="">Item 1</a></li> <li class="item2"><a href="">Item 2</a></li> <li class="item3"><a href="">Item 3</a></li> <li class="item4"><a href="">Item 4</a></li> </ul> ``` ## Features * **Familiar syntax**: as a web-developer, you already know how to use Emmet. Abbreviation syntax is similar to CSS Selectors with shortcuts for id, class, custom attributes, element nesting and so on. * **Dynamic snippets**: unlike default editor snippets, Emmet abbreviations are dynamic and parsed as-you-type. No need to predefine them for each project, just type `MyComponent>custom-element` to convert any word into a tag. * **CSS properties shortcuts**: Emmet provides special syntax for CSS properties with embedded values. For example, `bd1-s#f.5` will be expanded to `border: 1px solid rgba(255, 255, 255, 0.5)`. * **Available for most popular syntaxes**: use single abbreviation to produce code for most popular syntaxes like HAML, Pug, JSX, SCSS, SASS etc. [Read more about Emmet features](https://docs.emmet.io) This repo contains only core module for parsing and expanding Emmet abbreviations. Editor plugins are available as [separate repos](https://github.com/emmetio). This is a *monorepo*: top-level project contains all the code required for converting abbreviation into code fragment while [`./packages`](/packages) folder contains modules for parsing abbreviations into AST and can be used independently (for example, as lexer for syntax highlighting). ### Installation You can install Emmet as a regular npm module: ```bash npm i emmet@rc ``` Note that current version is still in *release candidate* version so it should be installed with `@rc` tag. After release, it will be available as version 2.x. ## Usage To expand abbreviation, pass it to default function of `emmet` module: ```js import expand from 'emmet'; console.log(expand('p>a')); // <p><a href=""></a></p> ``` By default, Emmet expands *markup* abbreviation, e.g. abbreviation used for producing nested elements with attributes (like HTML, XML, HAML etc.). If you want to expand *stylesheet* abbreviation, you should pass it as a `type` property of second argument: ```js import expand from 'emmet'; console.log(expand('p10', { type: 'stylesheet' })); // padding: 10px; ``` A stylesheet abbreviation has slightly different syntax compared to markup one: it doesn’t support nesting and attributes but allows embedded values in element name. Alternatively, Emmet supports *syntaxes* with predefined snippets and options: ```js import expand from 'emmet'; console.log(expand('p10', { syntax: 'css' })); // padding: 10px; console.log(expand('p10', { syntax: 'stylus' })); // padding 10px ``` Predefined syntaxes already have `type` attribute which describes whether given abbreviation is markup or stylesheet, but if you want to use it with your custom syntax name, you should provide `type` config option as well (default is `markup`): ```js import expand from 'emmet'; console.log(expand('p10', { syntax: 'my-custom-syntax', type: 'stylesheet', options: { 'stylesheet.between': '__', 'stylesheet.after': '', } })); // padding__10px ``` You can pass `options` property as well to shape-up final output or enable/disable various features. See [`src/config.ts`](src/config.ts) for more info and available options. ## Extracting abbreviations from text A common workflow with Emmet is to type abbreviation somewhere in source code and then expand it with editor action. To support such workflow, abbreviations must be properly _extracted_ from source code: ```js import expand, { extract } from 'emmet'; const source = 'Hello world ul.tabs>li'; const data = extract(source, 22); // { abbreviation: 'ul.tabs>li' } console.log(expand(data.abbreviation)); // <ul class="tabs"><li></li></ul> ``` The `extract` function accepts source code (most likely, current line) and character location in source from which abbreviation search should be started. The abbreviation is searched in backward direction: the location pointer is moved backward until it finds abbreviation bound. Returned result is an object with `abbreviation` property and `start` and `end` properties which describe location of extracted abbreviation in given source. Most current editors automatically insert closing quote or bracket for `(`, `[` and `{` characters so when user types abbreviation that uses attributes or text, it will end with the following state (`|` is caret location): ``` ul>li[title="Foo|"] ``` E.g. caret location is not at the end of abbreviation and must be moved a few characters ahead. The `extract` function is able to handle such cases with `lookAhead` option (enabled by default). This this option enabled, `extract` method automatically detects auto-inserted characters and adjusts location, which will be available as `end` property of the returned result: ```js import { extract } from 'emmet'; const source = 'a div[title] b'; const loc = 11; // right after "title" word // `lookAhead` is enabled by default console.log(extract(source, loc)); // { abbreviation: 'div[title]', start: 2, end: 12 } console.log(extract(source, loc, { lookAhead: false })); // { abbreviation: 'title', start: 6, end: 11 } ``` By default, `extract` tries to detect _markup_ abbreviations (see above). _stylesheet_ abbreviations has slightly different syntax so in order to extract abbreviations for stylesheet syntaxes like CSS, you should pass `type: 'stylesheet'` option: ```js import { extract } from 'emmet'; const source = 'a{b}'; const loc = 3; // right after "b" console.log(extract(source, loc)); // { abbreviation: 'a{b}', start: 0, end: 4 } // Stylesheet abbreviations does not have `{text}` syntax console.log(extract(source, loc, { type: 'stylesheet' })); // { abbreviation: 'b', start: 2, end: 3 } ``` ### Extract abbreviation with custom prefix Lots of developers uses React (or similar) library for writing UI code which mixes JS and XML (JSX) in the same source code. Since _any_ Latin word can be used as Emmet abbreviation, writing JSX code with Emmet becomes pain since it will interfere with native editor snippets and distract user with false positive abbreviation matches for variable names, methods etc.: ```js var div // `div` is a valid abbreviation, Emmet may transform it to `<div></div>` ``` A possible solution for this problem it to use _prefix_ for abbreviation: abbreviation can be successfully extracted only if its preceded with given prefix. ```js import { extract } from 'emmet'; const source1 = '() => div'; const source2 = '() => <div'; extract(source1, source1.length); // Finds `div` abbreviation extract(source2, source2.length); // Finds `div` abbreviation too extract(source1, source1.length, { prefix: '<' }); // No match, `div` abbreviation is not preceded with `<` prefix extract(source2, source2.length, { prefix: '<' }); // Finds `div` since it preceded with `<` prefix ``` With `prefix` option, you can customize your experience with Emmet in any common syntax (HTML, CSS and so on) if user is distracted too much with Emmet completions for any typed word. A `prefix` may contain multiple character but the last one *must* be a character which is not part of Emmet abbreviation. Good candidates are `<`, `&`, `→` (emoji or Unicode symbol) and so on. <MSG> Updated README <DFF> @@ -37,11 +37,9 @@ This is a *monorepo*: top-level project contains all the code required for conve You can install Emmet as a regular npm module: ```bash -npm i emmet@rc +npm i emmet ``` -Note that current version is still in *release candidate* version so it should be installed with `@rc` tag. After release, it will be available as version 2.x. - ## Usage To expand abbreviation, pass it to default function of `emmet` module:
1
Updated README
3
.md
md
mit
emmetio/emmet
10072086
<NME> README.md <BEF> # Emmet — the essential toolkit for web-developers Emmet is a web-developer’s toolkit for boosting HTML & CSS code writing. With Emmet, you can type expressions (_abbreviations_) similar to CSS selectors and convert them into code fragment with a single keystroke. For example, this abbreviation: ``` ul#nav>li.item$*4>a{Item $} ``` ...can be expanded into: ```html <ul id="nav"> <li class="item1"><a href="">Item 1</a></li> <li class="item2"><a href="">Item 2</a></li> <li class="item3"><a href="">Item 3</a></li> <li class="item4"><a href="">Item 4</a></li> </ul> ``` ## Features * **Familiar syntax**: as a web-developer, you already know how to use Emmet. Abbreviation syntax is similar to CSS Selectors with shortcuts for id, class, custom attributes, element nesting and so on. * **Dynamic snippets**: unlike default editor snippets, Emmet abbreviations are dynamic and parsed as-you-type. No need to predefine them for each project, just type `MyComponent>custom-element` to convert any word into a tag. * **CSS properties shortcuts**: Emmet provides special syntax for CSS properties with embedded values. For example, `bd1-s#f.5` will be expanded to `border: 1px solid rgba(255, 255, 255, 0.5)`. * **Available for most popular syntaxes**: use single abbreviation to produce code for most popular syntaxes like HAML, Pug, JSX, SCSS, SASS etc. [Read more about Emmet features](https://docs.emmet.io) This repo contains only core module for parsing and expanding Emmet abbreviations. Editor plugins are available as [separate repos](https://github.com/emmetio). This is a *monorepo*: top-level project contains all the code required for converting abbreviation into code fragment while [`./packages`](/packages) folder contains modules for parsing abbreviations into AST and can be used independently (for example, as lexer for syntax highlighting). ### Installation You can install Emmet as a regular npm module: ```bash npm i emmet@rc ``` Note that current version is still in *release candidate* version so it should be installed with `@rc` tag. After release, it will be available as version 2.x. ## Usage To expand abbreviation, pass it to default function of `emmet` module: ```js import expand from 'emmet'; console.log(expand('p>a')); // <p><a href=""></a></p> ``` By default, Emmet expands *markup* abbreviation, e.g. abbreviation used for producing nested elements with attributes (like HTML, XML, HAML etc.). If you want to expand *stylesheet* abbreviation, you should pass it as a `type` property of second argument: ```js import expand from 'emmet'; console.log(expand('p10', { type: 'stylesheet' })); // padding: 10px; ``` A stylesheet abbreviation has slightly different syntax compared to markup one: it doesn’t support nesting and attributes but allows embedded values in element name. Alternatively, Emmet supports *syntaxes* with predefined snippets and options: ```js import expand from 'emmet'; console.log(expand('p10', { syntax: 'css' })); // padding: 10px; console.log(expand('p10', { syntax: 'stylus' })); // padding 10px ``` Predefined syntaxes already have `type` attribute which describes whether given abbreviation is markup or stylesheet, but if you want to use it with your custom syntax name, you should provide `type` config option as well (default is `markup`): ```js import expand from 'emmet'; console.log(expand('p10', { syntax: 'my-custom-syntax', type: 'stylesheet', options: { 'stylesheet.between': '__', 'stylesheet.after': '', } })); // padding__10px ``` You can pass `options` property as well to shape-up final output or enable/disable various features. See [`src/config.ts`](src/config.ts) for more info and available options. ## Extracting abbreviations from text A common workflow with Emmet is to type abbreviation somewhere in source code and then expand it with editor action. To support such workflow, abbreviations must be properly _extracted_ from source code: ```js import expand, { extract } from 'emmet'; const source = 'Hello world ul.tabs>li'; const data = extract(source, 22); // { abbreviation: 'ul.tabs>li' } console.log(expand(data.abbreviation)); // <ul class="tabs"><li></li></ul> ``` The `extract` function accepts source code (most likely, current line) and character location in source from which abbreviation search should be started. The abbreviation is searched in backward direction: the location pointer is moved backward until it finds abbreviation bound. Returned result is an object with `abbreviation` property and `start` and `end` properties which describe location of extracted abbreviation in given source. Most current editors automatically insert closing quote or bracket for `(`, `[` and `{` characters so when user types abbreviation that uses attributes or text, it will end with the following state (`|` is caret location): ``` ul>li[title="Foo|"] ``` E.g. caret location is not at the end of abbreviation and must be moved a few characters ahead. The `extract` function is able to handle such cases with `lookAhead` option (enabled by default). This this option enabled, `extract` method automatically detects auto-inserted characters and adjusts location, which will be available as `end` property of the returned result: ```js import { extract } from 'emmet'; const source = 'a div[title] b'; const loc = 11; // right after "title" word // `lookAhead` is enabled by default console.log(extract(source, loc)); // { abbreviation: 'div[title]', start: 2, end: 12 } console.log(extract(source, loc, { lookAhead: false })); // { abbreviation: 'title', start: 6, end: 11 } ``` By default, `extract` tries to detect _markup_ abbreviations (see above). _stylesheet_ abbreviations has slightly different syntax so in order to extract abbreviations for stylesheet syntaxes like CSS, you should pass `type: 'stylesheet'` option: ```js import { extract } from 'emmet'; const source = 'a{b}'; const loc = 3; // right after "b" console.log(extract(source, loc)); // { abbreviation: 'a{b}', start: 0, end: 4 } // Stylesheet abbreviations does not have `{text}` syntax console.log(extract(source, loc, { type: 'stylesheet' })); // { abbreviation: 'b', start: 2, end: 3 } ``` ### Extract abbreviation with custom prefix Lots of developers uses React (or similar) library for writing UI code which mixes JS and XML (JSX) in the same source code. Since _any_ Latin word can be used as Emmet abbreviation, writing JSX code with Emmet becomes pain since it will interfere with native editor snippets and distract user with false positive abbreviation matches for variable names, methods etc.: ```js var div // `div` is a valid abbreviation, Emmet may transform it to `<div></div>` ``` A possible solution for this problem it to use _prefix_ for abbreviation: abbreviation can be successfully extracted only if its preceded with given prefix. ```js import { extract } from 'emmet'; const source1 = '() => div'; const source2 = '() => <div'; extract(source1, source1.length); // Finds `div` abbreviation extract(source2, source2.length); // Finds `div` abbreviation too extract(source1, source1.length, { prefix: '<' }); // No match, `div` abbreviation is not preceded with `<` prefix extract(source2, source2.length, { prefix: '<' }); // Finds `div` since it preceded with `<` prefix ``` With `prefix` option, you can customize your experience with Emmet in any common syntax (HTML, CSS and so on) if user is distracted too much with Emmet completions for any typed word. A `prefix` may contain multiple character but the last one *must* be a character which is not part of Emmet abbreviation. Good candidates are `<`, `&`, `→` (emoji or Unicode symbol) and so on. <MSG> Updated README <DFF> @@ -37,11 +37,9 @@ This is a *monorepo*: top-level project contains all the code required for conve You can install Emmet as a regular npm module: ```bash -npm i emmet@rc +npm i emmet ``` -Note that current version is still in *release candidate* version so it should be installed with `@rc` tag. After release, it will be available as version 2.x. - ## Usage To expand abbreviation, pass it to default function of `emmet` module:
1
Updated README
3
.md
md
mit
emmetio/emmet
10072087
<NME> setup.py <BEF> #!/usr/bin/env python # -*- coding: utf-8 -*- import os import codecs try: from setuptools import setup, find_packages except ImportError: from ez_setup import use_setuptools use_setuptools() from setuptools import setup, find_packages from distutils.command.install_data import install_data from distutils.command.install import INSTALL_SCHEMES import sys djangopypi = __import__('djangopypi', {}, {}, ['']) packages, data_files = [], [] root_dir = os.path.dirname(__file__) if root_dir != '': os.chdir(root_dir) djangopypi_dir = "djangopypi" def osx_install_data(install_data): def finalize_options(self): self.set_undefined_options("install", ("install_lib", "install_dir")) "Intended Audience :: Developers", "Intended Audience :: System Administrators", "License :: OSI Approved :: BSD License", "Programming Language :: Python", ], long_description=codecs.open('README', "r", "utf-8").read(), def fullsplit(path, result=None): if result is None: result = [] head, tail = os.path.split(path) if head == '': return [tail] + result if head == path: return result return fullsplit(head, [tail] + result) for scheme in INSTALL_SCHEMES.values(): scheme['data'] = scheme['purelib'] for dirpath, dirnames, filenames in os.walk(djangopypi_dir): # Ignore dirnames that start with '.' for i, dirname in enumerate(dirnames): if dirname.startswith("."): del dirnames[i] for filename in filenames: if filename.endswith(".py"): packages.append('.'.join(fullsplit(dirpath))) else: data_files.append([dirpath, [os.path.join(dirpath, f) for f in filenames]]) setup( name='chishop', version=djangopypi.__version__, description='Simple PyPI server written in Django.', author='Ask Solem', author_email='askh@opera.com', packages=packages, url="http://ask.github.com/chishop", zip_safe=False, data_files=data_files, install_requires=[ 'django>=1.0', 'docutils', 'django-registration>0.7', ], classifiers=[ "Development Status :: 3 - Alpha", "Environment :: Web Environment", "Framework :: Django", "Operating System :: OS Independent", "Intended Audience :: Developers", "Intended Audience :: System Administrators", "License :: OSI Approved :: BSD License", "Topic :: System :: Software Distribution", "Programming Language :: Python", ], long_description=codecs.open('README', "r", "utf-8").read(), ) <MSG> Added trove category Topic :: System :: Software Distribution <DFF> @@ -28,6 +28,7 @@ setup( "Intended Audience :: Developers", "Intended Audience :: System Administrators", "License :: OSI Approved :: BSD License", + "Topic :: System :: Software Distribution", "Programming Language :: Python", ], long_description=codecs.open('README', "r", "utf-8").read(),
1
Added trove category Topic :: System :: Software Distribution
0
.py
py
bsd-3-clause
ask/chishop
10072088
<NME> .gitignore <BEF> *.html.js .DS_Store .grunt /node_modules /dist *-SNAPSHOT* typings npm-debug.log .vscode src/**/*.js src/**/*.map <MSG> chore(.gitignore): Exclude .idea files <DFF> @@ -1,3 +1,4 @@ +.idea *.html.js .DS_Store .grunt
1
chore(.gitignore): Exclude .idea files
0
gitignore
mit
Semantic-Org/Semantic-UI-Angular
10072089
<NME> .gitignore <BEF> *.html.js .DS_Store .grunt /node_modules /dist *-SNAPSHOT* typings npm-debug.log .vscode src/**/*.js src/**/*.map <MSG> chore(.gitignore): Exclude .idea files <DFF> @@ -1,3 +1,4 @@ +.idea *.html.js .DS_Store .grunt
1
chore(.gitignore): Exclude .idea files
0
gitignore
mit
Semantic-Org/Semantic-UI-Angular
10072090
<NME> .gitignore <BEF> *.html.js .DS_Store .grunt /node_modules /dist *-SNAPSHOT* typings npm-debug.log .vscode src/**/*.js src/**/*.map <MSG> chore(.gitignore): Exclude .idea files <DFF> @@ -1,3 +1,4 @@ +.idea *.html.js .DS_Store .grunt
1
chore(.gitignore): Exclude .idea files
0
gitignore
mit
Semantic-Org/Semantic-UI-Angular
10072091
<NME> lorem.ts <BEF> import { ok, strictEqual as equal } from 'assert'; import expand from '../src'; function wordCount(str: string): number { return str.split(' ').length; } function splitLines(str: string): string[] { return str.split(/\n/); } describe('Lorem Ipsum generator', () => { it('single', () => { let output = expand('lorem'); ok(/^Lorem,?\sipsum/.test(output)); ok(wordCount(output) > 20); output = expand('lorem5'); ok(/^Lorem,?\sipsum/.test(output)); equal(wordCount(output), 5); output = expand('lorem5-10'); ok(/^Lorem,?\sipsum/.test(output)); ok(wordCount(output) >= 5 && wordCount(output) <= 10); output = expand('loremru4'); ok(/^Далеко-далеко,?\sза,?\sсловесными/.test(output)); equal(wordCount(output), 4); output = expand('p>lorem'); ok(/^<p>Lorem,?\sipsum/.test(output)); // https://github.com/emmetio/expand-abbreviation/issues/24 output = expand('(p)lorem2'); ok(/^<p><\/p>\nLorem,?\sipsum/.test(output)); output = expand('p(lorem10)'); ok(/^<p><\/p>\nLorem,?\sipsum/.test(output)); }); ok(/^Lorem,?\sipsum/.test(output)); equal(lines.length, 3); output = expand('p*3>lorem'); lines = splitLines(output); ok(/^<p>Lorem,?\sipsum/.test(lines[0]!)); output = expand('p*3>lorem'); lines = splitLines(output); ok(/^<p>Lorem,?\sipsum/.test(lines[0]!)); ok(!/^<p>Lorem,?\sipsum/.test(lines[1]!)); output = expand('ul>lorem5*3', { options: { 'output.indent': '' } }); lines = splitLines(output); equal(lines.length, 5); ok(/^<li>Lorem,?\sipsum/.test(lines[1]!)); ok(!/^<li>Lorem,?\sipsum/.test(lines[2]!)); }); }); <MSG> [markup] Format adjacent text-only/snippet nodes <DFF> @@ -40,6 +40,11 @@ describe('Lorem Ipsum generator', () => { ok(/^Lorem,?\sipsum/.test(output)); equal(lines.length, 3); + output = expand('lorem6*2'); + lines = splitLines(output); + ok(/^Lorem,?\sipsum/.test(output)); + equal(lines.length, 2); + output = expand('p*3>lorem'); lines = splitLines(output); ok(/^<p>Lorem,?\sipsum/.test(lines[0]!));
5
[markup] Format adjacent text-only/snippet nodes
0
.ts
ts
mit
emmetio/emmet
10072092
<NME> lorem.ts <BEF> import { ok, strictEqual as equal } from 'assert'; import expand from '../src'; function wordCount(str: string): number { return str.split(' ').length; } function splitLines(str: string): string[] { return str.split(/\n/); } describe('Lorem Ipsum generator', () => { it('single', () => { let output = expand('lorem'); ok(/^Lorem,?\sipsum/.test(output)); ok(wordCount(output) > 20); output = expand('lorem5'); ok(/^Lorem,?\sipsum/.test(output)); equal(wordCount(output), 5); output = expand('lorem5-10'); ok(/^Lorem,?\sipsum/.test(output)); ok(wordCount(output) >= 5 && wordCount(output) <= 10); output = expand('loremru4'); ok(/^Далеко-далеко,?\sза,?\sсловесными/.test(output)); equal(wordCount(output), 4); output = expand('p>lorem'); ok(/^<p>Lorem,?\sipsum/.test(output)); // https://github.com/emmetio/expand-abbreviation/issues/24 output = expand('(p)lorem2'); ok(/^<p><\/p>\nLorem,?\sipsum/.test(output)); output = expand('p(lorem10)'); ok(/^<p><\/p>\nLorem,?\sipsum/.test(output)); }); ok(/^Lorem,?\sipsum/.test(output)); equal(lines.length, 3); output = expand('p*3>lorem'); lines = splitLines(output); ok(/^<p>Lorem,?\sipsum/.test(lines[0]!)); output = expand('p*3>lorem'); lines = splitLines(output); ok(/^<p>Lorem,?\sipsum/.test(lines[0]!)); ok(!/^<p>Lorem,?\sipsum/.test(lines[1]!)); output = expand('ul>lorem5*3', { options: { 'output.indent': '' } }); lines = splitLines(output); equal(lines.length, 5); ok(/^<li>Lorem,?\sipsum/.test(lines[1]!)); ok(!/^<li>Lorem,?\sipsum/.test(lines[2]!)); }); }); <MSG> [markup] Format adjacent text-only/snippet nodes <DFF> @@ -40,6 +40,11 @@ describe('Lorem Ipsum generator', () => { ok(/^Lorem,?\sipsum/.test(output)); equal(lines.length, 3); + output = expand('lorem6*2'); + lines = splitLines(output); + ok(/^Lorem,?\sipsum/.test(output)); + equal(lines.length, 2); + output = expand('p*3>lorem'); lines = splitLines(output); ok(/^<p>Lorem,?\sipsum/.test(lines[0]!));
5
[markup] Format adjacent text-only/snippet nodes
0
.ts
ts
mit
emmetio/emmet
10072093
<NME> stylesheet.ts <BEF> import { strictEqual as equal, ok } from 'assert'; import { stylesheet as expandAbbreviation, resolveConfig, CSSAbbreviationScope } from '../src'; import score from '../src/stylesheet/score'; const defaultConfig = resolveConfig({ type: 'stylesheet', options: { 'output.field': (index, placeholder) => `\${${index}${placeholder ? ':' + placeholder : ''}}`, 'stylesheet.fuzzySearchMinScore': 0 }, snippets: { mten: 'margin: 10px;', fsz: 'font-size', gt: 'grid-template: repeat(2,auto) / repeat(auto-fit, minmax(250px, 1fr))' }, cache: {}, }); function expand(abbr: string, config = defaultConfig) { return expandAbbreviation(abbr, config); } describe('Stylesheet abbreviations', () => { describe('Scoring', () => { const pick = (abbr: string, items: string[]) => items .map(item => ({ item, score: score(abbr, item, true) })) .filter(obj => obj.score) .sort((a, b) => b.score - a.score) .map(obj => obj.item)[0]; it('compare scores', () => { equal(score('aaa', 'aaa'), 1); equal(score('baa', 'aaa'), 0); ok(!score('b', 'aaa')); ok(score('a', 'aaa')); ok(score('a', 'abc')); ok(score('ac', 'abc')); ok(score('a', 'aaa') < score('aa', 'aaa')); ok(score('ab', 'abc') > score('ab', 'acb')); // acronym bonus ok(score('ab', 'a-b') > score('ab', 'acb')); }); it('pick padding or position', () => { const items = ['p', 'pb', 'pl', 'pos', 'pa', 'oa', 'soa', 'pr', 'pt']; equal(pick('p', items), 'p'); equal(pick('poa', items), 'pos'); }); }); it('keywords', () => { equal(expand('bd1-s'), 'border: 1px solid;'); equal(expand('dib'), 'display: inline-block;'); equal(expand('bxsz'), 'box-sizing: ${1:border-box};'); equal(expand('bxz'), 'box-sizing: ${1:border-box};'); equal(expand('bxzc'), 'box-sizing: content-box;'); equal(expand('fl'), 'float: ${1:left};'); equal(expand('fll'), 'float: left;'); equal(expand('pos'), 'position: ${1:relative};'); equal(expand('poa'), 'position: absolute;'); equal(expand('por'), 'position: relative;'); equal(expand('pof'), 'position: fixed;'); equal(expand('pos-a'), 'position: absolute;'); equal(expand('m'), 'margin: ${0};'); equal(expand('m0'), 'margin: 0;'); // use `auto` as global keyword equal(expand('m0-a'), 'margin: 0 auto;'); equal(expand('m-a'), 'margin: auto;'); equal(expand('bg'), 'background: ${1:#000};'); equal(expand('bd'), 'border: ${1:1px} ${2:solid} ${3:#000};'); equal(expand('bd0-s#fc0'), 'border: 0 solid #fc0;'); equal(expand('bd0-dd#fc0'), 'border: 0 dot-dash #fc0;'); equal(expand('bd0-h#fc0'), 'border: 0 hidden #fc0;'); equal(expand('trf-trs'), 'transform: translate(${1:x}, ${2:y});'); // https://github.com/emmetio/emmet/issues/610 equal(expand('c'), 'color: ${1:#000};'); equal(expand('cr'), 'color: rgb(${1:0}, ${2:0}, ${3:0});'); equal(expand('p10p'), 'padding: 10%;', 'unit alias'); equal(expand('z10'), 'z-index: 10;', 'Unitless property'); equal(expand('p10r'), 'padding: 10rem;', 'unit alias'); equal(expand('mten'), 'margin: ${1:10px};', 'Ignore terminating `;` in snippet'); // https://github.com/microsoft/vscode/issues/59951 equal(expand('fz'), 'font-size: ${0};'); equal(expand('list:n'), 'list-style-type: none;'); equal(expand('fsz'), 'font-size: ${0};'); equal(expand('fsz12'), 'font-size: 12px;'); equal(expand('fs'), 'font-style: ${1:italic};'); }); it('numeric with format options', () => { equal(expand('fz10'), 'font-size: 10px;', '`px` for integers'); equal(expand('fz1.'), 'font-size: 1em;', '`em` for explicit float'); equal(expand('p10p'), 'padding: 10%;', 'unit alias'); equal(expand('z10'), 'z-index: 10;', 'Unitless property'); equal(expand('p10r'), 'padding: 10rem;', 'unit alias'); equal(expand('mten'), 'margin: 10px;', 'Ignore terminating `;` in snippet'); // https://github.com/microsoft/vscode/issues/59951 equal(expand('fz'), 'font-size: ${0};'); equal(expand('fz12'), 'font-size: 12px;'); equal(expand('fsz'), 'font-size: ${0};'); equal(expand('fsz12'), 'font-size: 12px;'); equal(expand('fs'), 'font-style: ${1:italic};'); // https://github.com/emmetio/emmet/issues/558 equal(expand('us'), 'user-select: none;'); // https://github.com/microsoft/vscode/issues/105697 equal(expand('opa1'), 'opacity: 1;', 'Unitless property'); equal(expand('opa.1'), 'opacity: 0.1;', 'Unitless property'); equal(expand('opa.a'), 'opacity: .a;', 'Unitless property'); }); it('numeric with format options', () => { const config = resolveConfig({ type: 'stylesheet', options: { 'stylesheet.intUnit': 'pt', 'stylesheet.floatUnit': 'vh', 'stylesheet.unitAliases': { e: 'em', p: '%', x: 'ex', r: ' / @rem' } } }); equal(expand('p0', config), 'padding: 0;', 'No unit for 0'); equal(expand('p10', config), 'padding: 10pt;', '`pt` unit for integers'); equal(expand('p.4', config), 'padding: 0.4vh;', '`vh` for floats'); equal(expand('p10p', config), 'padding: 10%;', 'unit alias'); equal(expand('z10', config), 'z-index: 10;', 'Unitless property'); equal(expand('p10r', config), 'padding: 10 / @rem;', 'unit alias'); }); it('important', () => { equal(expand('!'), '!important'); equal(expand('p!'), 'padding: ${0} !important;'); equal(expand('p0!'), 'padding: 0 !important;'); }); it('color', () => { equal(expand('c'), 'color: ${1:#000};'); equal(expand('c#'), 'color: #000;'); equal(expand('c#f.5'), 'color: rgba(255, 255, 255, 0.5);'); equal(expand('c#f.5!'), 'color: rgba(255, 255, 255, 0.5) !important;'); equal(expand('bgc'), 'background-color: #${1:fff};'); }); it('snippets', () => { equal(expand('@'), '@media ${1:screen} {\n\t${0}\n}'); // Insert value into snippet fields equal(expand('@k-name'), '@keyframes name {\n\t${2}\n}'); equal(expand('@k-name10'), '@keyframes name {\n\t10\n}'); equal(expand('gt'), 'grid-template: repeat(2, auto) / repeat(auto-fit, minmax(250px, 1fr));'); }); it('multiple properties', () => { equal(expand('p10+m10-20'), 'padding: 10px;\nmargin: 10px 20px;'); equal(expand('p+bd'), 'padding: ${0};\nborder: ${1:1px} ${2:solid} ${3:#000};'); }); it('functions', () => { equal(expand('trf-s(2)'), 'transform: scale(2, ${2:y});'); equal(expand('trf-s(2, 3)'), 'transform: scale(2, 3);'); }); it('case insensitive matches', () => { equal(expand('trf:rx'), 'transform: rotateX(${1:angle});'); }); it('gradient resolver', () => { equal(expand('lg'), 'background-image: linear-gradient(${0});'); equal(expand('lg(to right, #0, #f00.5)'), 'background-image: linear-gradient(to right, #000, rgba(255, 0, 0, 0.5));'); }); it('unmatched abbreviation', () => { // This example is useless: it’s unexpected to receive `align-self: unset` // for `auto` snippet // equal(expand('auto', resolveConfig({ // type: 'stylesheet', // options: { 'stylesheet.fuzzySearchMinScore': 0 } // })), 'align-self: unset;'); equal(expand('auto'), 'auto: ${0};'); }); it('CSS-in-JS', () => { const config = resolveConfig({ type: 'stylesheet', options: { 'stylesheet.json': true, 'stylesheet.between': ': ' } }); equal(expand('p10+mt10-20', config), 'padding: 10,\nmarginTop: \'10px 20px\','); equal(expand('bgc', config), 'backgroundColor: \'#fff\','); }); it('resolve context value', () => { const config = resolveConfig({ type: 'stylesheet', context: { name: 'align-content' } }); equal(expand('s', config), 'start'); equal(expand('a', config), 'auto'); }); it('limit snippets by scope', () => { const sectionScope = resolveConfig({ type: 'stylesheet', context: { name: CSSAbbreviationScope.Section }, snippets: { mten: 'margin: 10px;', fsz: 'font-size', myCenterAwesome: 'body {\n\tdisplay: grid;\n}' } }); const propertyScope = resolveConfig({ type: 'stylesheet', context: { name: CSSAbbreviationScope.Property }, snippets: { mten: 'margin: 10px;', fsz: 'font-size', myCenterAwesome: 'body {\n\tdisplay: grid;\n}' } }); equal(expand('m', sectionScope), 'body {\n\tdisplay: grid;\n}'); equal(expand('b', sectionScope), ''); equal(expand('m', propertyScope), 'margin: ;'); }); }); <MSG> [stylesheet] Do not select single unmatched value in snippet Fixes #558 <DFF> @@ -88,7 +88,7 @@ describe('Stylesheet abbreviations', () => { equal(expand('p10p'), 'padding: 10%;', 'unit alias'); equal(expand('z10'), 'z-index: 10;', 'Unitless property'); equal(expand('p10r'), 'padding: 10rem;', 'unit alias'); - equal(expand('mten'), 'margin: ${1:10px};', 'Ignore terminating `;` in snippet'); + equal(expand('mten'), 'margin: 10px;', 'Ignore terminating `;` in snippet'); // https://github.com/microsoft/vscode/issues/59951 equal(expand('fz'), 'font-size: ${0};'); @@ -96,6 +96,9 @@ describe('Stylesheet abbreviations', () => { 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;'); }); it('numeric with format options', () => {
4
[stylesheet] Do not select single unmatched value in snippet
1
.ts
ts
mit
emmetio/emmet
10072094
<NME> stylesheet.ts <BEF> import { strictEqual as equal, ok } from 'assert'; import { stylesheet as expandAbbreviation, resolveConfig, CSSAbbreviationScope } from '../src'; import score from '../src/stylesheet/score'; const defaultConfig = resolveConfig({ type: 'stylesheet', options: { 'output.field': (index, placeholder) => `\${${index}${placeholder ? ':' + placeholder : ''}}`, 'stylesheet.fuzzySearchMinScore': 0 }, snippets: { mten: 'margin: 10px;', fsz: 'font-size', gt: 'grid-template: repeat(2,auto) / repeat(auto-fit, minmax(250px, 1fr))' }, cache: {}, }); function expand(abbr: string, config = defaultConfig) { return expandAbbreviation(abbr, config); } describe('Stylesheet abbreviations', () => { describe('Scoring', () => { const pick = (abbr: string, items: string[]) => items .map(item => ({ item, score: score(abbr, item, true) })) .filter(obj => obj.score) .sort((a, b) => b.score - a.score) .map(obj => obj.item)[0]; it('compare scores', () => { equal(score('aaa', 'aaa'), 1); equal(score('baa', 'aaa'), 0); ok(!score('b', 'aaa')); ok(score('a', 'aaa')); ok(score('a', 'abc')); ok(score('ac', 'abc')); ok(score('a', 'aaa') < score('aa', 'aaa')); ok(score('ab', 'abc') > score('ab', 'acb')); // acronym bonus ok(score('ab', 'a-b') > score('ab', 'acb')); }); it('pick padding or position', () => { const items = ['p', 'pb', 'pl', 'pos', 'pa', 'oa', 'soa', 'pr', 'pt']; equal(pick('p', items), 'p'); equal(pick('poa', items), 'pos'); }); }); it('keywords', () => { equal(expand('bd1-s'), 'border: 1px solid;'); equal(expand('dib'), 'display: inline-block;'); equal(expand('bxsz'), 'box-sizing: ${1:border-box};'); equal(expand('bxz'), 'box-sizing: ${1:border-box};'); equal(expand('bxzc'), 'box-sizing: content-box;'); equal(expand('fl'), 'float: ${1:left};'); equal(expand('fll'), 'float: left;'); equal(expand('pos'), 'position: ${1:relative};'); equal(expand('poa'), 'position: absolute;'); equal(expand('por'), 'position: relative;'); equal(expand('pof'), 'position: fixed;'); equal(expand('pos-a'), 'position: absolute;'); equal(expand('m'), 'margin: ${0};'); equal(expand('m0'), 'margin: 0;'); // use `auto` as global keyword equal(expand('m0-a'), 'margin: 0 auto;'); equal(expand('m-a'), 'margin: auto;'); equal(expand('bg'), 'background: ${1:#000};'); equal(expand('bd'), 'border: ${1:1px} ${2:solid} ${3:#000};'); equal(expand('bd0-s#fc0'), 'border: 0 solid #fc0;'); equal(expand('bd0-dd#fc0'), 'border: 0 dot-dash #fc0;'); equal(expand('bd0-h#fc0'), 'border: 0 hidden #fc0;'); equal(expand('trf-trs'), 'transform: translate(${1:x}, ${2:y});'); // https://github.com/emmetio/emmet/issues/610 equal(expand('c'), 'color: ${1:#000};'); equal(expand('cr'), 'color: rgb(${1:0}, ${2:0}, ${3:0});'); equal(expand('p10p'), 'padding: 10%;', 'unit alias'); equal(expand('z10'), 'z-index: 10;', 'Unitless property'); equal(expand('p10r'), 'padding: 10rem;', 'unit alias'); equal(expand('mten'), 'margin: ${1:10px};', 'Ignore terminating `;` in snippet'); // https://github.com/microsoft/vscode/issues/59951 equal(expand('fz'), 'font-size: ${0};'); equal(expand('list:n'), 'list-style-type: none;'); equal(expand('fsz'), 'font-size: ${0};'); equal(expand('fsz12'), 'font-size: 12px;'); equal(expand('fs'), 'font-style: ${1:italic};'); }); it('numeric with format options', () => { equal(expand('fz10'), 'font-size: 10px;', '`px` for integers'); equal(expand('fz1.'), 'font-size: 1em;', '`em` for explicit float'); equal(expand('p10p'), 'padding: 10%;', 'unit alias'); equal(expand('z10'), 'z-index: 10;', 'Unitless property'); equal(expand('p10r'), 'padding: 10rem;', 'unit alias'); equal(expand('mten'), 'margin: 10px;', 'Ignore terminating `;` in snippet'); // https://github.com/microsoft/vscode/issues/59951 equal(expand('fz'), 'font-size: ${0};'); equal(expand('fz12'), 'font-size: 12px;'); equal(expand('fsz'), 'font-size: ${0};'); equal(expand('fsz12'), 'font-size: 12px;'); equal(expand('fs'), 'font-style: ${1:italic};'); // https://github.com/emmetio/emmet/issues/558 equal(expand('us'), 'user-select: none;'); // https://github.com/microsoft/vscode/issues/105697 equal(expand('opa1'), 'opacity: 1;', 'Unitless property'); equal(expand('opa.1'), 'opacity: 0.1;', 'Unitless property'); equal(expand('opa.a'), 'opacity: .a;', 'Unitless property'); }); it('numeric with format options', () => { const config = resolveConfig({ type: 'stylesheet', options: { 'stylesheet.intUnit': 'pt', 'stylesheet.floatUnit': 'vh', 'stylesheet.unitAliases': { e: 'em', p: '%', x: 'ex', r: ' / @rem' } } }); equal(expand('p0', config), 'padding: 0;', 'No unit for 0'); equal(expand('p10', config), 'padding: 10pt;', '`pt` unit for integers'); equal(expand('p.4', config), 'padding: 0.4vh;', '`vh` for floats'); equal(expand('p10p', config), 'padding: 10%;', 'unit alias'); equal(expand('z10', config), 'z-index: 10;', 'Unitless property'); equal(expand('p10r', config), 'padding: 10 / @rem;', 'unit alias'); }); it('important', () => { equal(expand('!'), '!important'); equal(expand('p!'), 'padding: ${0} !important;'); equal(expand('p0!'), 'padding: 0 !important;'); }); it('color', () => { equal(expand('c'), 'color: ${1:#000};'); equal(expand('c#'), 'color: #000;'); equal(expand('c#f.5'), 'color: rgba(255, 255, 255, 0.5);'); equal(expand('c#f.5!'), 'color: rgba(255, 255, 255, 0.5) !important;'); equal(expand('bgc'), 'background-color: #${1:fff};'); }); it('snippets', () => { equal(expand('@'), '@media ${1:screen} {\n\t${0}\n}'); // Insert value into snippet fields equal(expand('@k-name'), '@keyframes name {\n\t${2}\n}'); equal(expand('@k-name10'), '@keyframes name {\n\t10\n}'); equal(expand('gt'), 'grid-template: repeat(2, auto) / repeat(auto-fit, minmax(250px, 1fr));'); }); it('multiple properties', () => { equal(expand('p10+m10-20'), 'padding: 10px;\nmargin: 10px 20px;'); equal(expand('p+bd'), 'padding: ${0};\nborder: ${1:1px} ${2:solid} ${3:#000};'); }); it('functions', () => { equal(expand('trf-s(2)'), 'transform: scale(2, ${2:y});'); equal(expand('trf-s(2, 3)'), 'transform: scale(2, 3);'); }); it('case insensitive matches', () => { equal(expand('trf:rx'), 'transform: rotateX(${1:angle});'); }); it('gradient resolver', () => { equal(expand('lg'), 'background-image: linear-gradient(${0});'); equal(expand('lg(to right, #0, #f00.5)'), 'background-image: linear-gradient(to right, #000, rgba(255, 0, 0, 0.5));'); }); it('unmatched abbreviation', () => { // This example is useless: it’s unexpected to receive `align-self: unset` // for `auto` snippet // equal(expand('auto', resolveConfig({ // type: 'stylesheet', // options: { 'stylesheet.fuzzySearchMinScore': 0 } // })), 'align-self: unset;'); equal(expand('auto'), 'auto: ${0};'); }); it('CSS-in-JS', () => { const config = resolveConfig({ type: 'stylesheet', options: { 'stylesheet.json': true, 'stylesheet.between': ': ' } }); equal(expand('p10+mt10-20', config), 'padding: 10,\nmarginTop: \'10px 20px\','); equal(expand('bgc', config), 'backgroundColor: \'#fff\','); }); it('resolve context value', () => { const config = resolveConfig({ type: 'stylesheet', context: { name: 'align-content' } }); equal(expand('s', config), 'start'); equal(expand('a', config), 'auto'); }); it('limit snippets by scope', () => { const sectionScope = resolveConfig({ type: 'stylesheet', context: { name: CSSAbbreviationScope.Section }, snippets: { mten: 'margin: 10px;', fsz: 'font-size', myCenterAwesome: 'body {\n\tdisplay: grid;\n}' } }); const propertyScope = resolveConfig({ type: 'stylesheet', context: { name: CSSAbbreviationScope.Property }, snippets: { mten: 'margin: 10px;', fsz: 'font-size', myCenterAwesome: 'body {\n\tdisplay: grid;\n}' } }); equal(expand('m', sectionScope), 'body {\n\tdisplay: grid;\n}'); equal(expand('b', sectionScope), ''); equal(expand('m', propertyScope), 'margin: ;'); }); }); <MSG> [stylesheet] Do not select single unmatched value in snippet Fixes #558 <DFF> @@ -88,7 +88,7 @@ describe('Stylesheet abbreviations', () => { equal(expand('p10p'), 'padding: 10%;', 'unit alias'); equal(expand('z10'), 'z-index: 10;', 'Unitless property'); equal(expand('p10r'), 'padding: 10rem;', 'unit alias'); - equal(expand('mten'), 'margin: ${1:10px};', 'Ignore terminating `;` in snippet'); + equal(expand('mten'), 'margin: 10px;', 'Ignore terminating `;` in snippet'); // https://github.com/microsoft/vscode/issues/59951 equal(expand('fz'), 'font-size: ${0};'); @@ -96,6 +96,9 @@ describe('Stylesheet abbreviations', () => { 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;'); }); it('numeric with format options', () => {
4
[stylesheet] Do not select single unmatched value in snippet
1
.ts
ts
mit
emmetio/emmet
10072095
<NME> .gitignore <BEF> ._ .DS_Store .swp <MSG> ignore vim swp files <DFF> @@ -1,3 +1,3 @@ ._ .DS_Store -.swp +*.swp
1
ignore vim swp files
1
gitignore
mit
zacstewart/Meow
10072096
<NME> .gitignore <BEF> ._ .DS_Store .swp <MSG> ignore vim swp files <DFF> @@ -1,3 +1,3 @@ ._ .DS_Store -.swp +*.swp
1
ignore vim swp files
1
gitignore
mit
zacstewart/Meow
10072097
<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" Dir["./spec/support/*.rb"].each { |f| require f } module GlobalSharedContext extend RSpec::SharedContext let(:mock_user) { Split::User.new(double(session: {})) } 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 end def session 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> Merge pull request #677 from splitrb/fix-spec-deprecations Remove usage of deprecated implicit block expectation from specs <DFF> @@ -31,6 +31,7 @@ end RSpec.configure do |config| config.order = 'random' config.include GlobalSharedContext + config.raise_errors_for_deprecations! end def session
1
Merge pull request #677 from splitrb/fix-spec-deprecations
0
.rb
rb
mit
splitrb/split
10072098
<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" Dir["./spec/support/*.rb"].each { |f| require f } module GlobalSharedContext extend RSpec::SharedContext let(:mock_user) { Split::User.new(double(session: {})) } 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 end def session 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> Merge pull request #677 from splitrb/fix-spec-deprecations Remove usage of deprecated implicit block expectation from specs <DFF> @@ -31,6 +31,7 @@ end RSpec.configure do |config| config.order = 'random' config.include GlobalSharedContext + config.raise_errors_for_deprecations! end def session
1
Merge pull request #677 from splitrb/fix-spec-deprecations
0
.rb
rb
mit
splitrb/split
10072099
<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" Dir["./spec/support/*.rb"].each { |f| require f } module GlobalSharedContext extend RSpec::SharedContext let(:mock_user) { Split::User.new(double(session: {})) } 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 end def session 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> Merge pull request #677 from splitrb/fix-spec-deprecations Remove usage of deprecated implicit block expectation from specs <DFF> @@ -31,6 +31,7 @@ end RSpec.configure do |config| config.order = 'random' config.include GlobalSharedContext + config.raise_errors_for_deprecations! end def session
1
Merge pull request #677 from splitrb/fix-spec-deprecations
0
.rb
rb
mit
splitrb/split
10072100
<NME> snippets.ts <BEF> ADDFILE <MSG> Working on CSS snippet resolver <DFF> @@ -0,0 +1,168 @@ +import parse, { CSSValue, ParseOptions } from '@emmetio/css-abbreviation'; + +export type CSSSnippet = CSSSnippetRaw | CSSSnippetProperty; + +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[][]; + dependencies: CSSSnippetProperty[]; +} + +export interface CSSKeywordRef { + keyword: string; + + /** Reference to CSS snippet value which contains current keyword */ + index: number; +} + +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) { + return { + type: CSSSnippetType.Property, + key, + property: m[1], + value: m[2].split('|').map(parseValue), + dependencies: [] + }; + } + + return { type: CSSSnippetType.Raw, key, value }; +} + +/** + * Returns list of unique keywords for current CSS snippet and its dependencies + */ +export function getKeywords(snippet: CSSSnippet): CSSKeywordRef[] { + const stack: CSSSnippetProperty[] = []; + const result: CSSKeywordRef[] = []; + const lookup: Set<string> = new Set(); + let i = 0; + + if (snippet.type === CSSSnippetType.Property) { + // Scan valid CSS-properties only + stack.push(snippet); + } + + while (i < stack.length) { + // NB Keep items in stack instead of push/pop to avoid possible + // circular references + const item = stack[i++]; + + // Extract possible keywords from snippet values + for (let index = 0; index < item.value.length; index++) { + for (const keyword of keywordsFromValue(item.value[index])) { + if (!lookup.has(keyword)) { + result.push({ index, keyword }); + lookup.add(keyword); + } + } + } + + // Add dependencies into scan stack + for (const dep of item.dependencies) { + if (!stack.includes(dep)) { + stack.push(dep); + } + } + } + + return result; +} + +function keywordsFromValue(value: CSSValue[]): string[] { + const keywords: string[] = []; + for (const v of value) { + for (const kw of v.value) { + if (kw.type === 'Literal') { + keywords.push(kw.value); + } else if (kw.type === 'FunctionCall') { + keywords.push(kw.name); + } + } + } + + return keywords; +} + +/** + * 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; +}
168
Working on CSS snippet resolver
0
.ts
ts
mit
emmetio/emmet
10072101
<NME> snippets.ts <BEF> ADDFILE <MSG> Working on CSS snippet resolver <DFF> @@ -0,0 +1,168 @@ +import parse, { CSSValue, ParseOptions } from '@emmetio/css-abbreviation'; + +export type CSSSnippet = CSSSnippetRaw | CSSSnippetProperty; + +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[][]; + dependencies: CSSSnippetProperty[]; +} + +export interface CSSKeywordRef { + keyword: string; + + /** Reference to CSS snippet value which contains current keyword */ + index: number; +} + +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) { + return { + type: CSSSnippetType.Property, + key, + property: m[1], + value: m[2].split('|').map(parseValue), + dependencies: [] + }; + } + + return { type: CSSSnippetType.Raw, key, value }; +} + +/** + * Returns list of unique keywords for current CSS snippet and its dependencies + */ +export function getKeywords(snippet: CSSSnippet): CSSKeywordRef[] { + const stack: CSSSnippetProperty[] = []; + const result: CSSKeywordRef[] = []; + const lookup: Set<string> = new Set(); + let i = 0; + + if (snippet.type === CSSSnippetType.Property) { + // Scan valid CSS-properties only + stack.push(snippet); + } + + while (i < stack.length) { + // NB Keep items in stack instead of push/pop to avoid possible + // circular references + const item = stack[i++]; + + // Extract possible keywords from snippet values + for (let index = 0; index < item.value.length; index++) { + for (const keyword of keywordsFromValue(item.value[index])) { + if (!lookup.has(keyword)) { + result.push({ index, keyword }); + lookup.add(keyword); + } + } + } + + // Add dependencies into scan stack + for (const dep of item.dependencies) { + if (!stack.includes(dep)) { + stack.push(dep); + } + } + } + + return result; +} + +function keywordsFromValue(value: CSSValue[]): string[] { + const keywords: string[] = []; + for (const v of value) { + for (const kw of v.value) { + if (kw.type === 'Literal') { + keywords.push(kw.value); + } else if (kw.type === 'FunctionCall') { + keywords.push(kw.name); + } + } + } + + return keywords; +} + +/** + * 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; +}
168
Working on CSS snippet resolver
0
.ts
ts
mit
emmetio/emmet
10072102
<NME> output-stream.ts <BEF> ADDFILE <MSG> HTML outout (WIP) <DFF> @@ -0,0 +1,61 @@ +import { FormatOptions, Options } from './types'; + +const formatOptions: FormatOptions = { + indent: '\t', + baseIndent: '', + newline: '\n', + field(index: number, placeholder: string) { + return placeholder ? `\${${index}:${placeholder}}` : `\${${index}}`; + } +}; + +export interface OutputStream { + format: FormatOptions; + value: string; + offset: number; + line: number; + column: number; +} + +export default function createOutputStream(options: Options): OutputStream { + return { + format: { ...formatOptions, ...options }, + value: '', + offset: 0, + line: 0, + column: 0 + }; +} + +/** + * Pushes given string into output + */ +export function pushString(stream: OutputStream, value: string) { + stream.value += value; + stream.offset += value.length; + stream.column += value.length; +} + +/** + * Pushes new line into given output stream + */ +export function pushNewline(stream: OutputStream) { + const { baseIndent, newline } = stream.format; + pushString(stream, newline + baseIndent); + stream.line++; + stream.column = baseIndent.length; +} + +/** + * Adds indentation of `size` to current output stream + */ +export function pushIndent(stream: OutputStream, size: number = 1) { + pushString(stream, stream.format.indent.repeat(size)); +} + +/** + * Pushes field/tabstop into output stream + */ +export function pushField(stream: OutputStream, index: number, placeholder: string) { + pushString(stream, stream.format.field(index, placeholder, stream.offset, stream.line, stream.column)); +}
61
HTML outout (WIP)
0
.ts
ts
mit
emmetio/emmet
10072103
<NME> output-stream.ts <BEF> ADDFILE <MSG> HTML outout (WIP) <DFF> @@ -0,0 +1,61 @@ +import { FormatOptions, Options } from './types'; + +const formatOptions: FormatOptions = { + indent: '\t', + baseIndent: '', + newline: '\n', + field(index: number, placeholder: string) { + return placeholder ? `\${${index}:${placeholder}}` : `\${${index}}`; + } +}; + +export interface OutputStream { + format: FormatOptions; + value: string; + offset: number; + line: number; + column: number; +} + +export default function createOutputStream(options: Options): OutputStream { + return { + format: { ...formatOptions, ...options }, + value: '', + offset: 0, + line: 0, + column: 0 + }; +} + +/** + * Pushes given string into output + */ +export function pushString(stream: OutputStream, value: string) { + stream.value += value; + stream.offset += value.length; + stream.column += value.length; +} + +/** + * Pushes new line into given output stream + */ +export function pushNewline(stream: OutputStream) { + const { baseIndent, newline } = stream.format; + pushString(stream, newline + baseIndent); + stream.line++; + stream.column = baseIndent.length; +} + +/** + * Adds indentation of `size` to current output stream + */ +export function pushIndent(stream: OutputStream, size: number = 1) { + pushString(stream, stream.format.indent.repeat(size)); +} + +/** + * Pushes field/tabstop into output stream + */ +export function pushField(stream: OutputStream, index: number, placeholder: string) { + pushString(stream, stream.format.field(index, placeholder, stream.offset, stream.line, stream.column)); +}
61
HTML outout (WIP)
0
.ts
ts
mit
emmetio/emmet
10072104
<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 'Slurp' => 'Yahoo spider', 'Sogou' => 'Chinese search engine', 'spider' => 'generic web spider', 'UnwindFetchor' => 'Gnip crawler' 'WordPress' => 'WordPress spider', 'YandexBot' => 'Yandex spider', 'ZIBB' => 'ZIBB spider', "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> Fixed syntax error <DFF> @@ -37,7 +37,7 @@ module Split 'Slurp' => 'Yahoo spider', 'Sogou' => 'Chinese search engine', 'spider' => 'generic web spider', - 'UnwindFetchor' => 'Gnip crawler' + 'UnwindFetchor' => 'Gnip crawler', 'WordPress' => 'WordPress spider', 'YandexBot' => 'Yandex spider', 'ZIBB' => 'ZIBB spider',
1
Fixed syntax error
1
.rb
rb
mit
splitrb/split
10072105
<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 'Slurp' => 'Yahoo spider', 'Sogou' => 'Chinese search engine', 'spider' => 'generic web spider', 'UnwindFetchor' => 'Gnip crawler' 'WordPress' => 'WordPress spider', 'YandexBot' => 'Yandex spider', 'ZIBB' => 'ZIBB spider', "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> Fixed syntax error <DFF> @@ -37,7 +37,7 @@ module Split 'Slurp' => 'Yahoo spider', 'Sogou' => 'Chinese search engine', 'spider' => 'generic web spider', - 'UnwindFetchor' => 'Gnip crawler' + 'UnwindFetchor' => 'Gnip crawler', 'WordPress' => 'WordPress spider', 'YandexBot' => 'Yandex spider', 'ZIBB' => 'ZIBB spider',
1
Fixed syntax error
1
.rb
rb
mit
splitrb/split
10072106
<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 'Slurp' => 'Yahoo spider', 'Sogou' => 'Chinese search engine', 'spider' => 'generic web spider', 'UnwindFetchor' => 'Gnip crawler' 'WordPress' => 'WordPress spider', 'YandexBot' => 'Yandex spider', 'ZIBB' => 'ZIBB spider', "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> Fixed syntax error <DFF> @@ -37,7 +37,7 @@ module Split 'Slurp' => 'Yahoo spider', 'Sogou' => 'Chinese search engine', 'spider' => 'generic web spider', - 'UnwindFetchor' => 'Gnip crawler' + 'UnwindFetchor' => 'Gnip crawler', 'WordPress' => 'WordPress spider', 'YandexBot' => 'Yandex spider', 'ZIBB' => 'ZIBB spider',
1
Fixed syntax error
1
.rb
rb
mit
splitrb/split
10072107
<NME> indexPage.template.html <BEF> ADDFILE <MSG> chore(dgeni): Created basic index page <DFF> @@ -0,0 +1,27 @@ +<!DOCTYPE html> +<html> +<head lang="en"> + <meta charset="UTF-8"> + <title>Semantic-UI-Angular</title> + <link rel="stylesheet" href="lib/semantic-ui/semantic.css"/> +</head> +<body> +<div class="ui page grid"> + <div class="menu ui"> + <h1 class="header item">Semantic-UI-Angular</h1> + <a class="item active" href="#"><i class="lab icon"></i>API Documentation</a> + <span class="right menu"> + <div class="item">v. 0.0.0</div> + </span> + </div> + <div class="ui grid"> + <div class="sixteen wide column"> + <div class="ui segment" ng-include="'partials/api.html'"></div> + </div> + <div class="sixteen wide column"> + <div class="ui right aligned segment">Built by <span><a href="https://github.com/angular/dgeni">Dgeni</a></span> - Open Source &copy;2014</div> + </div> + </div> +</div> +</body> +</html> \ No newline at end of file
27
chore(dgeni): Created basic index page
0
.html
template
mit
Semantic-Org/Semantic-UI-Angular
10072108
<NME> indexPage.template.html <BEF> ADDFILE <MSG> chore(dgeni): Created basic index page <DFF> @@ -0,0 +1,27 @@ +<!DOCTYPE html> +<html> +<head lang="en"> + <meta charset="UTF-8"> + <title>Semantic-UI-Angular</title> + <link rel="stylesheet" href="lib/semantic-ui/semantic.css"/> +</head> +<body> +<div class="ui page grid"> + <div class="menu ui"> + <h1 class="header item">Semantic-UI-Angular</h1> + <a class="item active" href="#"><i class="lab icon"></i>API Documentation</a> + <span class="right menu"> + <div class="item">v. 0.0.0</div> + </span> + </div> + <div class="ui grid"> + <div class="sixteen wide column"> + <div class="ui segment" ng-include="'partials/api.html'"></div> + </div> + <div class="sixteen wide column"> + <div class="ui right aligned segment">Built by <span><a href="https://github.com/angular/dgeni">Dgeni</a></span> - Open Source &copy;2014</div> + </div> + </div> +</div> +</body> +</html> \ No newline at end of file
27
chore(dgeni): Created basic index page
0
.html
template
mit
Semantic-Org/Semantic-UI-Angular
10072109
<NME> indexPage.template.html <BEF> ADDFILE <MSG> chore(dgeni): Created basic index page <DFF> @@ -0,0 +1,27 @@ +<!DOCTYPE html> +<html> +<head lang="en"> + <meta charset="UTF-8"> + <title>Semantic-UI-Angular</title> + <link rel="stylesheet" href="lib/semantic-ui/semantic.css"/> +</head> +<body> +<div class="ui page grid"> + <div class="menu ui"> + <h1 class="header item">Semantic-UI-Angular</h1> + <a class="item active" href="#"><i class="lab icon"></i>API Documentation</a> + <span class="right menu"> + <div class="item">v. 0.0.0</div> + </span> + </div> + <div class="ui grid"> + <div class="sixteen wide column"> + <div class="ui segment" ng-include="'partials/api.html'"></div> + </div> + <div class="sixteen wide column"> + <div class="ui right aligned segment">Built by <span><a href="https://github.com/angular/dgeni">Dgeni</a></span> - Open Source &copy;2014</div> + </div> + </div> +</div> +</body> +</html> \ No newline at end of file
27
chore(dgeni): Created basic index page
0
.html
template
mit
Semantic-Org/Semantic-UI-Angular
10072110
<NME> tests.py <BEF> import unittest import StringIO from djangopypi.views import parse_distutils_request, simple from djangopypi.models import Project, Classifier from django.test.client import Client from django.core.urlresolvers import reverse from django.contrib.auth.models import User from django.http import HttpRequest def create_post_data(action): data = { ":action": action, "metadata_version": "1.0", "name": "foo", "version": "0.1.0-pre2", "summary": "The quick brown fox jumps over the lazy dog.", "home_page": "http://example.com", "author": "Foo Bar Baz", "author_email": "foobarbaz@example.com", "license": "Apache", "keywords": "foo bar baz", "platform": "UNKNOWN", "classifiers": [ "Development Status :: 3 - Alpha", "Environment :: Web Environment", "Framework :: Django", "Operating System :: OS Independent", "Intended Audience :: Developers", "Intended Audience :: System Administrators", "License :: OSI Approved :: BSD License", "Topic :: System :: Software Distribution", "Programming Language :: Python", ], "download_url": "", "provides": "", "requires": "", "obsoletes": "", "description": """ ========= FOOBARBAZ ========= Introduction ------------ ``foo`` :class:`bar` *baz* [foaoa] """, } return data def create_request(data): boundary = '--------------GHSKFJDLGDS7543FJKLFHRE75642756743254' sep_boundary = '\n--' + boundary end_boundary = sep_boundary + '--' body = StringIO.StringIO() for key, value in data.items(): # handle multiple entries for the same name if type(value) not in (type([]), type( () )): value = [value] for value in value: value = unicode(value).encode("utf-8") body.write(sep_boundary) body.write('\nContent-Disposition: form-data; name="%s"'%key) body.write("\n\n") body.write(value) if value and value[-1] == '\r': body.write('\n') # write an extra newline (lurve Macs) body.write(end_boundary) body.write("\n") return body.getvalue() class MockRequest(object): def __init__(self, raw_post_data): self.raw_post_data = raw_post_data self.META = {} data = create_post_data("submit") raw_post_data = create_request(data) post, files = parse_distutils_request(MockRequest(raw_post_data)) print("post: %s files: %s" % (post, files)) self.assertTrue(post) for key in post.keys(): if isinstance(data[key], list): self.assertEquals(data[key], post.getlist(key)) else: self.assertEquals(post[key], data[key]) self.assertEquals(data[key], post.getlist(key)) elif data[key] == "UNKNOWN": self.assertTrue(post[key] is None) else: self.assertEquals(post[key], data[key]) client = Client() class TestSearch(unittest.TestCase): def setUp(self): dummy_user = User.objects.create(username='krill', password='12345', email='krill@opera.com') Project.objects.create(name='foo', license='Gnu', summary="The quick brown fox jumps over the lazy dog.", owner=dummy_user) def test_search_for_package(self): response = client.post(reverse('djangopypi-search'), {'search_term': 'foo'}) self.assertTrue("The quick brown fox jumps over the lazy dog." in response.content) class TestSimpleView(unittest.TestCase): def create_distutils_httprequest(self, user_data={}): self.post_data = create_post_data(action='user') self.post_data.update(user_data) self.raw_post_data = create_request(self.post_data) request = HttpRequest() request.POST = self.post_data request.method = "POST" request.raw_post_data = self.raw_post_data return request def test_user_registration(self): request = self.create_distutils_httprequest({'name': 'peter_parker', 'email':'parker@dailybugle.com', 'password':'spiderman'}) response = simple(request) self.assertEquals(200, response.status_code) def test_user_registration_with_wrong_data(self): request = self.create_distutils_httprequest({'name': 'peter_parker', 'email':'parker@dailybugle.com', 'password':'',}) response = simple(request) self.assertEquals(400, response.status_code) <MSG> Fixes broken unittest. "test-suite" now passes again. <DFF> @@ -80,11 +80,12 @@ class TestParseWeirdPostData(unittest.TestCase): data = create_post_data("submit") raw_post_data = create_request(data) post, files = parse_distutils_request(MockRequest(raw_post_data)) - print("post: %s files: %s" % (post, files)) self.assertTrue(post) for key in post.keys(): if isinstance(data[key], list): self.assertEquals(data[key], post.getlist(key)) + elif data[key] == "UNKNOWN": + self.assertTrue(post[key] is None) else: self.assertEquals(post[key], data[key])
2
Fixes broken unittest. "test-suite" now passes again.
1
.py
py
bsd-3-clause
ask/chishop
10072111
<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('a>((((b>c))))+d'), '<a><b><c></c></b><d></d></a>'); equal(parse('a>(((b>c))*4)+d'), '<a><b*4@0><c></c></b><b*4@1><c></c></b><b*4@2><c></c></b><b*4@3><c></c></b><d></d></a>'); equal(parse('(div>dl>(dt+dd)*2)'), '<div><dl><dt*2@0></dt><dd*2@0></dd><dt*2@1></dt><dd*2@1></dd></dl></div>'); equal(parse('a*2>b*3'), '<a*2@0><b*3@0></b><b*3@1></b><b*3@2></b></a><a*2@1><b*3@0></b><b*3@1></b><b*3@2></b></a>'); equal(parse('a>(b+c)*2'), '<a><b*2@0></b><c*2@0></c><b*2@1></b><c*2@1></c></a>'); equal(parse('a>(b+c)*2+(d+e)*2'), '<a><b*2@0></b><c*2@0></c><b*2@1></b><c*2@1></c><d*2@0></d><e*2@0></e><d*2@1></d><e*2@1></e></a>'); // Should move `<div>` as sibling of `{foo}` 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', () => { 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('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> FIxed invalid parsing of repeater number with modifiers <DFF> @@ -47,6 +47,6 @@ describe('Convert token abbreviations', () => { 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>'); + 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>'); }); });
1
FIxed invalid parsing of repeater number with modifiers
1
.ts
ts
mit
emmetio/emmet
10072112
<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('a>((((b>c))))+d'), '<a><b><c></c></b><d></d></a>'); equal(parse('a>(((b>c))*4)+d'), '<a><b*4@0><c></c></b><b*4@1><c></c></b><b*4@2><c></c></b><b*4@3><c></c></b><d></d></a>'); equal(parse('(div>dl>(dt+dd)*2)'), '<div><dl><dt*2@0></dt><dd*2@0></dd><dt*2@1></dt><dd*2@1></dd></dl></div>'); equal(parse('a*2>b*3'), '<a*2@0><b*3@0></b><b*3@1></b><b*3@2></b></a><a*2@1><b*3@0></b><b*3@1></b><b*3@2></b></a>'); equal(parse('a>(b+c)*2'), '<a><b*2@0></b><c*2@0></c><b*2@1></b><c*2@1></c></a>'); equal(parse('a>(b+c)*2+(d+e)*2'), '<a><b*2@0></b><c*2@0></c><b*2@1></b><c*2@1></c><d*2@0></d><e*2@0></e><d*2@1></d><e*2@1></e></a>'); // Should move `<div>` as sibling of `{foo}` 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', () => { 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('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> FIxed invalid parsing of repeater number with modifiers <DFF> @@ -47,6 +47,6 @@ describe('Convert token abbreviations', () => { 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>'); + 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>'); }); });
1
FIxed invalid parsing of repeater number with modifiers
1
.ts
ts
mit
emmetio/emmet
10072113
<NME> expand.ts <BEF> import { strictEqual as equal } from 'assert'; import expand, { resolveConfig } from '../src'; describe('Expand Abbreviation', () => { describe('Markup', () => { it('basic', () => { equal(expand('input[value="text$"]*2'), '<input type="text" value="text1"><input type="text" value="text2">'); equal(expand('ul>.item$*2'), '<ul>\n\t<li class="item1"></li>\n\t<li class="item2"></li>\n</ul>'); // insert text into abbreviation equal(expand('ul>.item$*', { text: ['foo', 'bar'] }), '<ul>\n\t<li class="item1">foo</li>\n\t<li class="item2">bar</li>\n</ul>'); // insert TextMate-style fields/tabstops in output equal(expand('ul>.item$*2', { options: { 'output.field': (index, placeholder) => `\${${index}${placeholder ? ':' + placeholder : ''}}` } }), '<ul>\n\t<li class="item1">${1}</li>\n\t<li class="item2">${2}</li>\n</ul>'); }); it('attributes', () => { const snippets = { test: 'test[!foo bar. baz={}]' }; const opt = { snippets }; const reverse = { options: { 'output.reverseAttributes': true }, snippets }; equal(expand('a.test'), '<a href="" class="test"></a>'); equal(expand('a.test', reverse), '<a class="test" href=""></a>'); equal(expand('test', opt), '<test bar="bar" baz={}></test>'); equal(expand('test[foo]', opt), '<test bar="bar" baz={}></test>'); equal(expand('test[baz=a foo=1]', opt), '<test foo="1" bar="bar" baz={a}></test>'); equal(expand('map'), '<map name=""></map>'); equal(expand('map[]'), '<map name=""></map>'); equal(expand('map[name="valid"]'), '<map name="valid"></map>'); equal(expand('map[href="invalid"]'), '<map name="" href="invalid"></map>'); // Apply attributes in reverse order equal(expand('test', reverse), '<test bar="bar" baz={}></test>'); equal(expand('test[foo]', reverse), '<test bar="bar" baz={}></test>'); equal(expand('test[baz=a foo=1]', reverse), '<test baz={a} foo="1" bar="bar"></test>'); }); it('numbering', () => { equal(expand('ul>li.item$@-*5'), '<ul>\n\t<li class="item5"></li>\n\t<li class="item4"></li>\n\t<li class="item3"></li>\n\t<li class="item2"></li>\n\t<li class="item1"></li>\n</ul>'); }); it('syntax', () => { equal(expand('ul>.item$*2', { syntax: 'html' }), '<ul>\n\t<li class="item1"></li>\n\t<li class="item2"></li>\n</ul>'); equal(expand('ul>.item$*2', { syntax: 'slim' }), 'ul\n\tli.item1 \n\tli.item2 '); equal(expand('xsl:variable[name=a select=b]>div', { syntax: 'xsl' }), '<xsl:variable name="a">\n\t<div></div>\n</xsl:variable>'); }); it('custom profile', () => { equal(expand('img'), '<img src="" alt="">'); equal(expand('img', { options: { 'output.selfClosingStyle': 'xhtml' } }), '<img src="" alt="" />'); }); it('custom variables', () => { const variables = { charset: 'ru-RU' }; equal(expand('[charset=${charset}]{${charset}}'), '<div charset="UTF-8">UTF-8</div>'); equal(expand('[charset=${charset}]{${charset}}', { variables }), '<div charset="ru-RU">ru-RU</div>'); }); it('custom snippets', () => { const snippets = { link: 'link[foo=bar href]/', foo: '.foo[bar=baz]', repeat: 'div>ul>li{Hello World}*3' }; equal(expand('foo', { snippets }), '<div class="foo" bar="baz"></div>'); // `link:css` depends on `link` snippet so changing it will result in // altered `link:css` result equal(expand('link:css'), '<link rel="stylesheet" href="style.css">'); equal(expand('link:css', { snippets }), '<link foo="bar" href="style.css">'); // https://github.com/emmetio/emmet/issues/468 equal(expand('repeat', { snippets }), '<div>\n\t<ul>\n\t\t<li>Hello World</li>\n\t\t<li>Hello World</li>\n\t\t<li>Hello World</li>\n\t</ul>\n</div>'); }); it('formatter options', () => { equal(expand('ul>.item$*2'), '<ul>\n\t<li class="item1"></li>\n\t<li class="item2"></li>\n</ul>'); equal(expand('ul>.item$*2', { options: { 'comment.enabled': true } }), '<ul>\n\t<li class="item1"></li>\n\t<!-- /.item1 -->\n\t<li class="item2"></li>\n\t<!-- /.item2 -->\n</ul>'); equal(expand('div>p'), '<div>\n\t<p></p>\n</div>'); equal(expand('div>p', { options: { 'output.formatLeafNode': true } }), '<div>\n\t<p>\n\t\t\n\t</p>\n</div>'); }); it('JSX', () => { const config = { syntax: 'jsx' }; equal(expand('div#foo.bar', config), '<div id="foo" className="bar"></div>'); equal(expand('label[for=a]', config), '<label htmlFor="a"></label>'); equal(expand('Foo.Bar', config), '<Foo.Bar></Foo.Bar>'); equal(expand('div.{theme.style}', config), '<div className={theme.style}></div>'); }); 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>'); }); 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(name="viewport", content="width=device-width, initial-scale=1.0")\n\t\ttitle Document\n\tbody '); }); }); }); equal(expand('p', { text: 'foo<div>foo</div>' }), '<p>foo<div>foo</div></p>'); }); it('wrap with abbreviation href', () => { equal(expand('a', { text: ['www.google.it'] }), '<a href="http://www.google.it">www.google.it</a>'); equal(expand('a', { text: ['then www.google.it'] }), '<a href="">then www.google.it</a>'); equal(expand('a', { text: ['www.google.it'], options: { 'markup.href': false } }), '<a href="">www.google.it</a>'); equal(expand('map[name="https://example.com"]', { text: ['some text'] }), '<map name="https://example.com">some text</map>'); equal(expand('map[href="https://example.com"]', { text: ['some text'] }), '<map name="" href="https://example.com">some text</map>'); equal(expand('map[name="https://example.com"]>b', { text: ['some text'] }), '<map name="https://example.com"><b>some text</b></map>'); equal(expand('a[href="https://example.com"]>b', { text: ['<u>some text false</u>'], options: { 'markup.href': false } }), '<a href="https://example.com"><b><u>some text false</u></b></a>'); equal(expand('a[href="https://example.com"]>b', { text: ['<u>some text true</u>'], options: { 'markup.href': true } }), '<a href="https://example.com"><b><u>some text true</u></b></a>'); equal(expand('a[href="https://example.com"]>div', { text: ['<p>some text false</p>'], options: { 'markup.href': false } }), '<a href="https://example.com">\n\t<div>\n\t\t<p>some text false</p>\n\t</div>\n</a>'); equal(expand('a[href="https://example.com"]>div', { text: ['<p>some text true</p>'], options: { 'markup.href': true } }), '<a href="https://example.com">\n\t<div>\n\t\t<p>some text true</p>\n\t</div>\n</a>'); }); // it.only('debug', () => { // equal(expand('link:css'), '<link rel="stylesheet" href="style.css">'); // }); }); describe('Pug templates', () => { const config = resolveConfig({ syntax: 'pug' }); it('basic', () => { equal(expand('!', config), 'doctype html\nhtml(lang="en")\n\thead\n\t\tmeta(charset="UTF-8")\n\t\tmeta(http-equiv="X-UA-Compatible", content="IE=edge")\n\t\tmeta(name="viewport", content="width=device-width, initial-scale=1.0")\n\t\ttitle Document\n\tbody '); }); }); }); <MSG> Fix #619 (#624) <DFF> @@ -116,7 +116,7 @@ describe('Expand Abbreviation', () => { 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(name="viewport", content="width=device-width, initial-scale=1.0")\n\t\ttitle Document\n\tbody '); + 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 '); }); }); });
1
Fix #619 (#624)
1
.ts
ts
mit
emmetio/emmet
10072114
<NME> expand.ts <BEF> import { strictEqual as equal } from 'assert'; import expand, { resolveConfig } from '../src'; describe('Expand Abbreviation', () => { describe('Markup', () => { it('basic', () => { equal(expand('input[value="text$"]*2'), '<input type="text" value="text1"><input type="text" value="text2">'); equal(expand('ul>.item$*2'), '<ul>\n\t<li class="item1"></li>\n\t<li class="item2"></li>\n</ul>'); // insert text into abbreviation equal(expand('ul>.item$*', { text: ['foo', 'bar'] }), '<ul>\n\t<li class="item1">foo</li>\n\t<li class="item2">bar</li>\n</ul>'); // insert TextMate-style fields/tabstops in output equal(expand('ul>.item$*2', { options: { 'output.field': (index, placeholder) => `\${${index}${placeholder ? ':' + placeholder : ''}}` } }), '<ul>\n\t<li class="item1">${1}</li>\n\t<li class="item2">${2}</li>\n</ul>'); }); it('attributes', () => { const snippets = { test: 'test[!foo bar. baz={}]' }; const opt = { snippets }; const reverse = { options: { 'output.reverseAttributes': true }, snippets }; equal(expand('a.test'), '<a href="" class="test"></a>'); equal(expand('a.test', reverse), '<a class="test" href=""></a>'); equal(expand('test', opt), '<test bar="bar" baz={}></test>'); equal(expand('test[foo]', opt), '<test bar="bar" baz={}></test>'); equal(expand('test[baz=a foo=1]', opt), '<test foo="1" bar="bar" baz={a}></test>'); equal(expand('map'), '<map name=""></map>'); equal(expand('map[]'), '<map name=""></map>'); equal(expand('map[name="valid"]'), '<map name="valid"></map>'); equal(expand('map[href="invalid"]'), '<map name="" href="invalid"></map>'); // Apply attributes in reverse order equal(expand('test', reverse), '<test bar="bar" baz={}></test>'); equal(expand('test[foo]', reverse), '<test bar="bar" baz={}></test>'); equal(expand('test[baz=a foo=1]', reverse), '<test baz={a} foo="1" bar="bar"></test>'); }); it('numbering', () => { equal(expand('ul>li.item$@-*5'), '<ul>\n\t<li class="item5"></li>\n\t<li class="item4"></li>\n\t<li class="item3"></li>\n\t<li class="item2"></li>\n\t<li class="item1"></li>\n</ul>'); }); it('syntax', () => { equal(expand('ul>.item$*2', { syntax: 'html' }), '<ul>\n\t<li class="item1"></li>\n\t<li class="item2"></li>\n</ul>'); equal(expand('ul>.item$*2', { syntax: 'slim' }), 'ul\n\tli.item1 \n\tli.item2 '); equal(expand('xsl:variable[name=a select=b]>div', { syntax: 'xsl' }), '<xsl:variable name="a">\n\t<div></div>\n</xsl:variable>'); }); it('custom profile', () => { equal(expand('img'), '<img src="" alt="">'); equal(expand('img', { options: { 'output.selfClosingStyle': 'xhtml' } }), '<img src="" alt="" />'); }); it('custom variables', () => { const variables = { charset: 'ru-RU' }; equal(expand('[charset=${charset}]{${charset}}'), '<div charset="UTF-8">UTF-8</div>'); equal(expand('[charset=${charset}]{${charset}}', { variables }), '<div charset="ru-RU">ru-RU</div>'); }); it('custom snippets', () => { const snippets = { link: 'link[foo=bar href]/', foo: '.foo[bar=baz]', repeat: 'div>ul>li{Hello World}*3' }; equal(expand('foo', { snippets }), '<div class="foo" bar="baz"></div>'); // `link:css` depends on `link` snippet so changing it will result in // altered `link:css` result equal(expand('link:css'), '<link rel="stylesheet" href="style.css">'); equal(expand('link:css', { snippets }), '<link foo="bar" href="style.css">'); // https://github.com/emmetio/emmet/issues/468 equal(expand('repeat', { snippets }), '<div>\n\t<ul>\n\t\t<li>Hello World</li>\n\t\t<li>Hello World</li>\n\t\t<li>Hello World</li>\n\t</ul>\n</div>'); }); it('formatter options', () => { equal(expand('ul>.item$*2'), '<ul>\n\t<li class="item1"></li>\n\t<li class="item2"></li>\n</ul>'); equal(expand('ul>.item$*2', { options: { 'comment.enabled': true } }), '<ul>\n\t<li class="item1"></li>\n\t<!-- /.item1 -->\n\t<li class="item2"></li>\n\t<!-- /.item2 -->\n</ul>'); equal(expand('div>p'), '<div>\n\t<p></p>\n</div>'); equal(expand('div>p', { options: { 'output.formatLeafNode': true } }), '<div>\n\t<p>\n\t\t\n\t</p>\n</div>'); }); it('JSX', () => { const config = { syntax: 'jsx' }; equal(expand('div#foo.bar', config), '<div id="foo" className="bar"></div>'); equal(expand('label[for=a]', config), '<label htmlFor="a"></label>'); equal(expand('Foo.Bar', config), '<Foo.Bar></Foo.Bar>'); equal(expand('div.{theme.style}', config), '<div className={theme.style}></div>'); }); 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>'); }); 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(name="viewport", content="width=device-width, initial-scale=1.0")\n\t\ttitle Document\n\tbody '); }); }); }); equal(expand('p', { text: 'foo<div>foo</div>' }), '<p>foo<div>foo</div></p>'); }); it('wrap with abbreviation href', () => { equal(expand('a', { text: ['www.google.it'] }), '<a href="http://www.google.it">www.google.it</a>'); equal(expand('a', { text: ['then www.google.it'] }), '<a href="">then www.google.it</a>'); equal(expand('a', { text: ['www.google.it'], options: { 'markup.href': false } }), '<a href="">www.google.it</a>'); equal(expand('map[name="https://example.com"]', { text: ['some text'] }), '<map name="https://example.com">some text</map>'); equal(expand('map[href="https://example.com"]', { text: ['some text'] }), '<map name="" href="https://example.com">some text</map>'); equal(expand('map[name="https://example.com"]>b', { text: ['some text'] }), '<map name="https://example.com"><b>some text</b></map>'); equal(expand('a[href="https://example.com"]>b', { text: ['<u>some text false</u>'], options: { 'markup.href': false } }), '<a href="https://example.com"><b><u>some text false</u></b></a>'); equal(expand('a[href="https://example.com"]>b', { text: ['<u>some text true</u>'], options: { 'markup.href': true } }), '<a href="https://example.com"><b><u>some text true</u></b></a>'); equal(expand('a[href="https://example.com"]>div', { text: ['<p>some text false</p>'], options: { 'markup.href': false } }), '<a href="https://example.com">\n\t<div>\n\t\t<p>some text false</p>\n\t</div>\n</a>'); equal(expand('a[href="https://example.com"]>div', { text: ['<p>some text true</p>'], options: { 'markup.href': true } }), '<a href="https://example.com">\n\t<div>\n\t\t<p>some text true</p>\n\t</div>\n</a>'); }); // it.only('debug', () => { // equal(expand('link:css'), '<link rel="stylesheet" href="style.css">'); // }); }); describe('Pug templates', () => { const config = resolveConfig({ syntax: 'pug' }); it('basic', () => { equal(expand('!', config), 'doctype html\nhtml(lang="en")\n\thead\n\t\tmeta(charset="UTF-8")\n\t\tmeta(http-equiv="X-UA-Compatible", content="IE=edge")\n\t\tmeta(name="viewport", content="width=device-width, initial-scale=1.0")\n\t\ttitle Document\n\tbody '); }); }); }); <MSG> Fix #619 (#624) <DFF> @@ -116,7 +116,7 @@ describe('Expand Abbreviation', () => { 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(name="viewport", content="width=device-width, initial-scale=1.0")\n\t\ttitle Document\n\tbody '); + 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 '); }); }); });
1
Fix #619 (#624)
1
.ts
ts
mit
emmetio/emmet
10072115
<NME> parser.ts <BEF> import { strictEqual as equal, throws } from 'assert'; import parser from '../src/parser'; import tokenizer from '../src/tokenizer'; import stringify from './assets/stringify'; import { ParserOptions } from '../src'; const parse = (abbr: string, options?: ParserOptions) => parser(tokenizer(abbr), options); const str = (abbr: string, options?: ParserOptions) => stringify(parse(abbr, options)); describe('Parser', () => { it('basic abbreviations', () => { equal(str('p'), '<p></p>'); equal(str('p{text}'), '<p>text</p>'); equal(str('h$'), '<h$></h$>'); equal(str('.nav'), '<? class=nav></?>'); equal(str('div.width1\\/2'), '<div class=width1/2></div>'); equal(str('#sample*3'), '<?*3 id=sample></?>'); // https://github.com/emmetio/emmet/issues/562 equal(str('li[repeat.for="todo of todoList"]'), '<li repeat.for="todo of todoList"></li>', 'Dots in attribute names'); equal(str('a>b'), '<a><b></b></a>'); equal(str('a+b'), '<a></a><b></b>'); equal(str('a+b>c+d'), '<a></a><b><c></c><d></d></b>'); equal(str('a>b>c+e'), '<a><b><c></c><e></e></b></a>'); equal(str('a>b>c^d'), '<a><b><c></c></b><d></d></a>'); equal(str('a>b>c^^^^d'), '<a><b><c></c></b></a><d></d>'); equal(str('a:b>c'), '<a:b><c></c></a:b>'); equal(str('ul.nav[title="foo"]'), '<ul class=nav title="foo"></ul>'); }); it('groups', () => { equal(str('a>(b>c)+d'), '<a>(<b><c></c></b>)<d></d></a>'); equal(str('(a>b)+(c>d)'), '(<a><b></b></a>)(<c><d></d></c>)'); equal(str('a>((b>c)(d>e))f'), '<a>((<b><c></c></b>)(<d><e></e></d>))<f></f></a>'); equal(str('a>((((b>c))))+d'), '<a>((((<b><c></c></b>))))<d></d></a>'); equal(str('a>(((b>c))*4)+d'), '<a>(((<b><c></c></b>))*4)<d></d></a>'); equal(str('(div>dl>(dt+dd)*2)'), '(<div><dl>(<dt></dt><dd></dd>)*2</dl></div>)'); equal(str('a>()'), '<a>()</a>'); }); it('attributes', () => { equal(str('[].foo'), '<? class=foo></?>'); equal(str('[a]'), '<? a></?>'); equal(str('[a b c [d]]'), '<? a b c [d]></?>'); equal(str('[a=b]'), '<? a=b></?>'); equal(str('[a=b c= d=e]'), '<? a=b c d=e></?>'); equal(str('[a=b.c d=тест]'), '<? a=b.c d=тест></?>'); equal(str('[[a]=b (c)=d]'), '<? [a]=b (c)=d></?>'); // Quoted attribute values equal(str('[a="b"]'), '<? a="b"></?>'); equal(str('[a="b" c=\'d\' e=""]'), '<? a="b" c=\'d\' e=""></?>'); equal(str('[[a]="b" (c)=\'d\']'), '<? [a]="b" (c)=\'d\'></?>'); // Mixed quoted equal(str('[a="foo\'bar" b=\'foo"bar\' c="foo\\\"bar"]'), '<? a="foo\'bar" b=\'foo"bar\' c="foo"bar"></?>'); // Boolean & implied attributes equal(str('[a. b.]'), '<? a. b.></?>'); equal(str('[!a !b.]'), '<? !a !b.></?>'); // Default values equal(str('["a.b"]'), '<? ?="a.b"></?>'); equal(str('[\'a.b\' "c=d" foo=bar "./test.html"]'), '<? ?=\'a.b\' ?="c=d" foo=bar ?="./test.html"></?>'); // Expressions as values equal(str('[foo={1 + 2} bar={fn(1, "foo")}]'), '<? foo={1 + 2} bar={fn(1, "foo")}></?>'); // Tabstops as unquoted values equal(str('[name=${1} value=${2:test}]'), '<? name=${1} value=${2:test}></?>'); }); it('malformed attributes', () => { equal(str('[a'), '<? a></?>'); equal(str('[a={foo]'), '<? a={foo]></?>'); throws(() => str('[a="foo]'), /Unclosed quote/); throws(() => str('[a=b=c]'), /Unexpected "Operator" token/); }); it('elements', () => { equal(str('div'), '<div></div>'); equal(str('div.foo'), '<div class=foo></div>'); equal(str('div#foo'), '<div id=foo></div>'); equal(str('div#foo.bar'), '<div id=foo class=bar></div>'); equal(str('div.foo#bar'), '<div class=foo id=bar></div>'); equal(str('div.foo.bar.baz'), '<div class=foo class=bar class=baz></div>'); equal(str('.foo'), '<? class=foo></?>'); equal(str('#foo'), '<? id=foo></?>'); equal(str('.foo_bar'), '<? class=foo_bar></?>'); equal(str('#foo.bar'), '<? id=foo class=bar></?>'); // Attribute shorthands equal(str('.'), '<? class></?>'); equal(str('#'), '<? id></?>'); equal(str('#.'), '<? id class></?>'); equal(str('.#.'), '<? class id class></?>'); equal(str('.a..'), '<? class=a class></?>'); // Elements with attributes equal(str('div[foo=bar]'), '<div foo=bar></div>'); equal(str('div.a[b=c]'), '<div class=a b=c></div>'); equal(str('div[b=c].a'), '<div b=c class=a></div>'); equal(str('div[a=b][c="d"]'), '<div a=b c="d"></div>'); equal(str('[b=c]'), '<? b=c></?>'); equal(str('.a[b=c]'), '<? class=a b=c></?>'); equal(str('[b=c].a#d'), '<? b=c class=a id=d></?>'); equal(str('[b=c]a'), '<? b=c></?><a></a>', 'Do not consume node name after attribute set'); // Element with text equal(str('div{foo}'), '<div>foo</div>'); equal(str('{foo}'), '<?>foo</?>'); // Mixed equal(str('div.foo{bar}'), '<div class=foo>bar</div>'); equal(str('.foo{bar}#baz'), '<? class=foo id=baz>bar</?>'); equal(str('.foo[b=c]{bar}'), '<? class=foo b=c>bar</?>'); // Repeated element equal(str('div.foo*3'), '<div*3 class=foo></div>'); equal(str('.foo*'), '<?* class=foo></?>'); equal(str('.a[b=c]*10'), '<?*10 class=a b=c></?>'); equal(str('.a*10[b=c]'), '<?*10 class=a b=c></?>'); equal(str('.a*10{text}'), '<?*10 class=a>text</?>'); // Self-closing element equal(str('div/'), '<div />'); equal(str('.foo/'), '<? class=foo />'); equal(str('.foo[bar]/'), '<? class=foo bar />'); equal(str('.foo/*3'), '<?*3 class=foo />'); equal(str('.foo*3/'), '<?*3 class=foo />'); throws(() => parse('/'), /Unexpected character/); }); it('JSX', () => { const opt = { jsx: true }; equal(str('foo.bar', opt), '<foo class=bar></foo>'); equal(str('Foo.bar', opt), '<Foo class=bar></Foo>'); equal(str('Foo.Bar', opt), '<Foo.Bar></Foo.Bar>'); equal(str('Foo.', opt), '<Foo class></Foo>'); equal(str('Foo.Bar.baz', opt), '<Foo.Bar class=baz></Foo.Bar>'); equal(str('Foo.Bar.Baz', opt), '<Foo.Bar.Baz></Foo.Bar.Baz>'); equal(str('.{theme.class}', opt), '<? class=theme.class></?>'); equal(str('#{id}', opt), '<? id=id></?>'); equal(str('Foo.{theme.class}', opt), '<Foo class=theme.class></Foo>'); }); it('errors', () => { throws(() => parse('str?'), /Unexpected character at 4/); throws(() => parse('foo,bar'), /Unexpected character at 4/); equal(str('foo\\,bar'), '<foo,bar></foo,bar>'); }); }); }); <MSG> Do not throw errors on missing closing brace <DFF> @@ -153,4 +153,11 @@ describe('Parser', () => { throws(() => parse('foo,bar'), /Unexpected character at 4/); equal(str('foo\\,bar'), '<foo,bar></foo,bar>'); }); + + it('missing braces', () => { + // Do not throw errors on missing closing braces + equal(str('div[title="test"'), '<div title="test"></div>'); + equal(str('div(foo'), '<div></div>(<foo></foo>)'); + equal(str('div{foo'), '<div>foo</div>'); + }); });
7
Do not throw errors on missing closing brace
0
.ts
ts
mit
emmetio/emmet
10072116
<NME> parser.ts <BEF> import { strictEqual as equal, throws } from 'assert'; import parser from '../src/parser'; import tokenizer from '../src/tokenizer'; import stringify from './assets/stringify'; import { ParserOptions } from '../src'; const parse = (abbr: string, options?: ParserOptions) => parser(tokenizer(abbr), options); const str = (abbr: string, options?: ParserOptions) => stringify(parse(abbr, options)); describe('Parser', () => { it('basic abbreviations', () => { equal(str('p'), '<p></p>'); equal(str('p{text}'), '<p>text</p>'); equal(str('h$'), '<h$></h$>'); equal(str('.nav'), '<? class=nav></?>'); equal(str('div.width1\\/2'), '<div class=width1/2></div>'); equal(str('#sample*3'), '<?*3 id=sample></?>'); // https://github.com/emmetio/emmet/issues/562 equal(str('li[repeat.for="todo of todoList"]'), '<li repeat.for="todo of todoList"></li>', 'Dots in attribute names'); equal(str('a>b'), '<a><b></b></a>'); equal(str('a+b'), '<a></a><b></b>'); equal(str('a+b>c+d'), '<a></a><b><c></c><d></d></b>'); equal(str('a>b>c+e'), '<a><b><c></c><e></e></b></a>'); equal(str('a>b>c^d'), '<a><b><c></c></b><d></d></a>'); equal(str('a>b>c^^^^d'), '<a><b><c></c></b></a><d></d>'); equal(str('a:b>c'), '<a:b><c></c></a:b>'); equal(str('ul.nav[title="foo"]'), '<ul class=nav title="foo"></ul>'); }); it('groups', () => { equal(str('a>(b>c)+d'), '<a>(<b><c></c></b>)<d></d></a>'); equal(str('(a>b)+(c>d)'), '(<a><b></b></a>)(<c><d></d></c>)'); equal(str('a>((b>c)(d>e))f'), '<a>((<b><c></c></b>)(<d><e></e></d>))<f></f></a>'); equal(str('a>((((b>c))))+d'), '<a>((((<b><c></c></b>))))<d></d></a>'); equal(str('a>(((b>c))*4)+d'), '<a>(((<b><c></c></b>))*4)<d></d></a>'); equal(str('(div>dl>(dt+dd)*2)'), '(<div><dl>(<dt></dt><dd></dd>)*2</dl></div>)'); equal(str('a>()'), '<a>()</a>'); }); it('attributes', () => { equal(str('[].foo'), '<? class=foo></?>'); equal(str('[a]'), '<? a></?>'); equal(str('[a b c [d]]'), '<? a b c [d]></?>'); equal(str('[a=b]'), '<? a=b></?>'); equal(str('[a=b c= d=e]'), '<? a=b c d=e></?>'); equal(str('[a=b.c d=тест]'), '<? a=b.c d=тест></?>'); equal(str('[[a]=b (c)=d]'), '<? [a]=b (c)=d></?>'); // Quoted attribute values equal(str('[a="b"]'), '<? a="b"></?>'); equal(str('[a="b" c=\'d\' e=""]'), '<? a="b" c=\'d\' e=""></?>'); equal(str('[[a]="b" (c)=\'d\']'), '<? [a]="b" (c)=\'d\'></?>'); // Mixed quoted equal(str('[a="foo\'bar" b=\'foo"bar\' c="foo\\\"bar"]'), '<? a="foo\'bar" b=\'foo"bar\' c="foo"bar"></?>'); // Boolean & implied attributes equal(str('[a. b.]'), '<? a. b.></?>'); equal(str('[!a !b.]'), '<? !a !b.></?>'); // Default values equal(str('["a.b"]'), '<? ?="a.b"></?>'); equal(str('[\'a.b\' "c=d" foo=bar "./test.html"]'), '<? ?=\'a.b\' ?="c=d" foo=bar ?="./test.html"></?>'); // Expressions as values equal(str('[foo={1 + 2} bar={fn(1, "foo")}]'), '<? foo={1 + 2} bar={fn(1, "foo")}></?>'); // Tabstops as unquoted values equal(str('[name=${1} value=${2:test}]'), '<? name=${1} value=${2:test}></?>'); }); it('malformed attributes', () => { equal(str('[a'), '<? a></?>'); equal(str('[a={foo]'), '<? a={foo]></?>'); throws(() => str('[a="foo]'), /Unclosed quote/); throws(() => str('[a=b=c]'), /Unexpected "Operator" token/); }); it('elements', () => { equal(str('div'), '<div></div>'); equal(str('div.foo'), '<div class=foo></div>'); equal(str('div#foo'), '<div id=foo></div>'); equal(str('div#foo.bar'), '<div id=foo class=bar></div>'); equal(str('div.foo#bar'), '<div class=foo id=bar></div>'); equal(str('div.foo.bar.baz'), '<div class=foo class=bar class=baz></div>'); equal(str('.foo'), '<? class=foo></?>'); equal(str('#foo'), '<? id=foo></?>'); equal(str('.foo_bar'), '<? class=foo_bar></?>'); equal(str('#foo.bar'), '<? id=foo class=bar></?>'); // Attribute shorthands equal(str('.'), '<? class></?>'); equal(str('#'), '<? id></?>'); equal(str('#.'), '<? id class></?>'); equal(str('.#.'), '<? class id class></?>'); equal(str('.a..'), '<? class=a class></?>'); // Elements with attributes equal(str('div[foo=bar]'), '<div foo=bar></div>'); equal(str('div.a[b=c]'), '<div class=a b=c></div>'); equal(str('div[b=c].a'), '<div b=c class=a></div>'); equal(str('div[a=b][c="d"]'), '<div a=b c="d"></div>'); equal(str('[b=c]'), '<? b=c></?>'); equal(str('.a[b=c]'), '<? class=a b=c></?>'); equal(str('[b=c].a#d'), '<? b=c class=a id=d></?>'); equal(str('[b=c]a'), '<? b=c></?><a></a>', 'Do not consume node name after attribute set'); // Element with text equal(str('div{foo}'), '<div>foo</div>'); equal(str('{foo}'), '<?>foo</?>'); // Mixed equal(str('div.foo{bar}'), '<div class=foo>bar</div>'); equal(str('.foo{bar}#baz'), '<? class=foo id=baz>bar</?>'); equal(str('.foo[b=c]{bar}'), '<? class=foo b=c>bar</?>'); // Repeated element equal(str('div.foo*3'), '<div*3 class=foo></div>'); equal(str('.foo*'), '<?* class=foo></?>'); equal(str('.a[b=c]*10'), '<?*10 class=a b=c></?>'); equal(str('.a*10[b=c]'), '<?*10 class=a b=c></?>'); equal(str('.a*10{text}'), '<?*10 class=a>text</?>'); // Self-closing element equal(str('div/'), '<div />'); equal(str('.foo/'), '<? class=foo />'); equal(str('.foo[bar]/'), '<? class=foo bar />'); equal(str('.foo/*3'), '<?*3 class=foo />'); equal(str('.foo*3/'), '<?*3 class=foo />'); throws(() => parse('/'), /Unexpected character/); }); it('JSX', () => { const opt = { jsx: true }; equal(str('foo.bar', opt), '<foo class=bar></foo>'); equal(str('Foo.bar', opt), '<Foo class=bar></Foo>'); equal(str('Foo.Bar', opt), '<Foo.Bar></Foo.Bar>'); equal(str('Foo.', opt), '<Foo class></Foo>'); equal(str('Foo.Bar.baz', opt), '<Foo.Bar class=baz></Foo.Bar>'); equal(str('Foo.Bar.Baz', opt), '<Foo.Bar.Baz></Foo.Bar.Baz>'); equal(str('.{theme.class}', opt), '<? class=theme.class></?>'); equal(str('#{id}', opt), '<? id=id></?>'); equal(str('Foo.{theme.class}', opt), '<Foo class=theme.class></Foo>'); }); it('errors', () => { throws(() => parse('str?'), /Unexpected character at 4/); throws(() => parse('foo,bar'), /Unexpected character at 4/); equal(str('foo\\,bar'), '<foo,bar></foo,bar>'); }); }); }); <MSG> Do not throw errors on missing closing brace <DFF> @@ -153,4 +153,11 @@ describe('Parser', () => { throws(() => parse('foo,bar'), /Unexpected character at 4/); equal(str('foo\\,bar'), '<foo,bar></foo,bar>'); }); + + it('missing braces', () => { + // Do not throw errors on missing closing braces + equal(str('div[title="test"'), '<div title="test"></div>'); + equal(str('div(foo'), '<div></div>(<foo></foo>)'); + equal(str('div{foo'), '<div>foo</div>'); + }); });
7
Do not throw errors on missing closing brace
0
.ts
ts
mit
emmetio/emmet
10072117
<NME> rating.ts <BEF> ADDFILE <MSG> Merge pull request #51 from mxth/rating Refactor rating component <DFF> @@ -0,0 +1,173 @@ +///<reference path="../../../typings/angularjs/angular.d.ts"/> + +'use strict'; + +const ratingConfig = { + max: 5, + size: '', + stateActive: 'active', + stateHover: 'selected', + stateHoverParent: 'selected', + type: 'star' +}; + +class SmRatingController { + static $inject = ['$scope', '$element', '$attrs']; + + hoverValue: number; + readonly: boolean; + + stateHoverParent: string; + + ratingStates: RatingState[]; + icons: Icon[]; + + ngModel: ng.INgModelController; + + constructor(public $scope: ng.IScope, public $element: ng.IAugmentedJQuery, public $attrs) { + const + ratingStates: RatingState[] = this.evalAttribute('ratingStates') || Array.apply(null, Array(this.evalAttribute('max'))), + stateActive = this.evalAttribute('stateActive'), + stateHover = this.evalAttribute('stateHover'), + stateHoverParent = this.evalAttribute('stateHoverParent'); + + if (angular.isDefined($attrs.readonly)) { + $scope.$watch($attrs.readonly, (readonly: boolean) => { + this.readonly = readonly; + }); + } + + this.icons = ratingStates.map((state, index): Icon => { + const + iconElm = angular.element('<i class="icon"></i>'), + value = index + 1; + + iconElm.on('mouseenter', () => { + $scope.$apply(() => { + if (!this.readonly) { + this.hoverValue = value; + this.$element.addClass(stateHoverParent); + this.updateStateHover(); + } + if (angular.isDefined(this.$attrs.onHover)) { + this.$scope.$eval(this.$attrs.onHover, { value: value }); + } + }); + }); + + iconElm.on('click', () => { + this.rate(value); + }); + + return angular.extend(<Icon>{ + element: iconElm, + index: index, + stateActive: stateActive, + stateHover: stateHover + }, state); + }); + + this.icons.forEach(icon => { + $element.append(icon.element); + }); + + $element + .addClass('ui rating') + .addClass($attrs.type || ratingConfig.type) + .addClass($attrs.size || ratingConfig.size) + .attr({ + 'aria-valuemax': this.icons.length, + 'aria-valuemin': 0, + role: 'slider', + tabindex: 0 + }) + .on('mouseleave', () => { + this.hoverValue = -1; + if (angular.isDefined($attrs.onLeave)) { + $scope.$evalAsync($attrs.onLeave); + } + $element.removeClass(stateHoverParent); + this.updateStateHover(); + }) + .on('keydown', (evt: any) => { + if (/(37|38|39|40)/.test(evt.which)) { + evt.preventDefault(); + evt.stopPropagation(); + this.rate(this.ngModel.$viewValue + (evt.which === 38 || evt.which === 39 ? 1 : -1)); + } + }); + } + + rate(value: number) { + if (!this.readonly && value >= 0 && value <= this.icons.length) { + this.ngModel.$setViewValue(value); + this.ngModel.$render(); + } + } + + init(ngModel: ng.INgModelController) { + this.ngModel = ngModel; + + ngModel.$render = () => { + const value = ngModel.$viewValue; + this.$element.attr('aria-valuenow', value); + + this.icons.forEach((icon: Icon, index) => { + icon.element[index < value ? 'addClass' : 'removeClass'](icon.stateActive); + }); + }; + + ngModel.$formatters.push((value) => { + if (angular.isNumber(value) && value % 1 !== 0) { + value = Math.round(value); + } + return value; + }); + } + + updateStateHover() { + this.icons.forEach((icon: Icon, index) => { + icon.element[index < this.hoverValue ? 'addClass' : 'removeClass'](icon.stateHover); + }); + } + + evalAttribute(attr: string) { + return angular.isDefined(this.$attrs[attr]) ? + this.$scope.$eval(this.$attrs[attr]) : + ratingConfig[attr]; + } +} + +class SmRatingDirective implements ng.IDirective { + static instance(): ng.IDirective { + return new SmRatingDirective; + } + + restrict = 'E'; + require = ['smRating', 'ngModel']; + controller = SmRatingController; + link = ( + scope: ng.IScope, + element: ng.IAugmentedJQuery, + attrs, + ctrls: [SmRatingController, ng.INgModelController] + ) => { + const [smRating, ngModel] = ctrls; + smRating.init(ngModel); + }; +} + +interface Icon extends RatingState { + index: number; + element: ng.IAugmentedJQuery; +} + +interface RatingState { + stateActive: string; + stateHover: string; +} + +export const smRatingModule = angular + .module('semantic.ui.modules.rating', []) + .directive('smRating', SmRatingDirective.instance) + .constant('ratingConfig', ratingConfig);
173
Merge pull request #51 from mxth/rating
0
.ts
ts
mit
Semantic-Org/Semantic-UI-Angular
10072118
<NME> rating.ts <BEF> ADDFILE <MSG> Merge pull request #51 from mxth/rating Refactor rating component <DFF> @@ -0,0 +1,173 @@ +///<reference path="../../../typings/angularjs/angular.d.ts"/> + +'use strict'; + +const ratingConfig = { + max: 5, + size: '', + stateActive: 'active', + stateHover: 'selected', + stateHoverParent: 'selected', + type: 'star' +}; + +class SmRatingController { + static $inject = ['$scope', '$element', '$attrs']; + + hoverValue: number; + readonly: boolean; + + stateHoverParent: string; + + ratingStates: RatingState[]; + icons: Icon[]; + + ngModel: ng.INgModelController; + + constructor(public $scope: ng.IScope, public $element: ng.IAugmentedJQuery, public $attrs) { + const + ratingStates: RatingState[] = this.evalAttribute('ratingStates') || Array.apply(null, Array(this.evalAttribute('max'))), + stateActive = this.evalAttribute('stateActive'), + stateHover = this.evalAttribute('stateHover'), + stateHoverParent = this.evalAttribute('stateHoverParent'); + + if (angular.isDefined($attrs.readonly)) { + $scope.$watch($attrs.readonly, (readonly: boolean) => { + this.readonly = readonly; + }); + } + + this.icons = ratingStates.map((state, index): Icon => { + const + iconElm = angular.element('<i class="icon"></i>'), + value = index + 1; + + iconElm.on('mouseenter', () => { + $scope.$apply(() => { + if (!this.readonly) { + this.hoverValue = value; + this.$element.addClass(stateHoverParent); + this.updateStateHover(); + } + if (angular.isDefined(this.$attrs.onHover)) { + this.$scope.$eval(this.$attrs.onHover, { value: value }); + } + }); + }); + + iconElm.on('click', () => { + this.rate(value); + }); + + return angular.extend(<Icon>{ + element: iconElm, + index: index, + stateActive: stateActive, + stateHover: stateHover + }, state); + }); + + this.icons.forEach(icon => { + $element.append(icon.element); + }); + + $element + .addClass('ui rating') + .addClass($attrs.type || ratingConfig.type) + .addClass($attrs.size || ratingConfig.size) + .attr({ + 'aria-valuemax': this.icons.length, + 'aria-valuemin': 0, + role: 'slider', + tabindex: 0 + }) + .on('mouseleave', () => { + this.hoverValue = -1; + if (angular.isDefined($attrs.onLeave)) { + $scope.$evalAsync($attrs.onLeave); + } + $element.removeClass(stateHoverParent); + this.updateStateHover(); + }) + .on('keydown', (evt: any) => { + if (/(37|38|39|40)/.test(evt.which)) { + evt.preventDefault(); + evt.stopPropagation(); + this.rate(this.ngModel.$viewValue + (evt.which === 38 || evt.which === 39 ? 1 : -1)); + } + }); + } + + rate(value: number) { + if (!this.readonly && value >= 0 && value <= this.icons.length) { + this.ngModel.$setViewValue(value); + this.ngModel.$render(); + } + } + + init(ngModel: ng.INgModelController) { + this.ngModel = ngModel; + + ngModel.$render = () => { + const value = ngModel.$viewValue; + this.$element.attr('aria-valuenow', value); + + this.icons.forEach((icon: Icon, index) => { + icon.element[index < value ? 'addClass' : 'removeClass'](icon.stateActive); + }); + }; + + ngModel.$formatters.push((value) => { + if (angular.isNumber(value) && value % 1 !== 0) { + value = Math.round(value); + } + return value; + }); + } + + updateStateHover() { + this.icons.forEach((icon: Icon, index) => { + icon.element[index < this.hoverValue ? 'addClass' : 'removeClass'](icon.stateHover); + }); + } + + evalAttribute(attr: string) { + return angular.isDefined(this.$attrs[attr]) ? + this.$scope.$eval(this.$attrs[attr]) : + ratingConfig[attr]; + } +} + +class SmRatingDirective implements ng.IDirective { + static instance(): ng.IDirective { + return new SmRatingDirective; + } + + restrict = 'E'; + require = ['smRating', 'ngModel']; + controller = SmRatingController; + link = ( + scope: ng.IScope, + element: ng.IAugmentedJQuery, + attrs, + ctrls: [SmRatingController, ng.INgModelController] + ) => { + const [smRating, ngModel] = ctrls; + smRating.init(ngModel); + }; +} + +interface Icon extends RatingState { + index: number; + element: ng.IAugmentedJQuery; +} + +interface RatingState { + stateActive: string; + stateHover: string; +} + +export const smRatingModule = angular + .module('semantic.ui.modules.rating', []) + .directive('smRating', SmRatingDirective.instance) + .constant('ratingConfig', ratingConfig);
173
Merge pull request #51 from mxth/rating
0
.ts
ts
mit
Semantic-Org/Semantic-UI-Angular
10072119
<NME> rating.ts <BEF> ADDFILE <MSG> Merge pull request #51 from mxth/rating Refactor rating component <DFF> @@ -0,0 +1,173 @@ +///<reference path="../../../typings/angularjs/angular.d.ts"/> + +'use strict'; + +const ratingConfig = { + max: 5, + size: '', + stateActive: 'active', + stateHover: 'selected', + stateHoverParent: 'selected', + type: 'star' +}; + +class SmRatingController { + static $inject = ['$scope', '$element', '$attrs']; + + hoverValue: number; + readonly: boolean; + + stateHoverParent: string; + + ratingStates: RatingState[]; + icons: Icon[]; + + ngModel: ng.INgModelController; + + constructor(public $scope: ng.IScope, public $element: ng.IAugmentedJQuery, public $attrs) { + const + ratingStates: RatingState[] = this.evalAttribute('ratingStates') || Array.apply(null, Array(this.evalAttribute('max'))), + stateActive = this.evalAttribute('stateActive'), + stateHover = this.evalAttribute('stateHover'), + stateHoverParent = this.evalAttribute('stateHoverParent'); + + if (angular.isDefined($attrs.readonly)) { + $scope.$watch($attrs.readonly, (readonly: boolean) => { + this.readonly = readonly; + }); + } + + this.icons = ratingStates.map((state, index): Icon => { + const + iconElm = angular.element('<i class="icon"></i>'), + value = index + 1; + + iconElm.on('mouseenter', () => { + $scope.$apply(() => { + if (!this.readonly) { + this.hoverValue = value; + this.$element.addClass(stateHoverParent); + this.updateStateHover(); + } + if (angular.isDefined(this.$attrs.onHover)) { + this.$scope.$eval(this.$attrs.onHover, { value: value }); + } + }); + }); + + iconElm.on('click', () => { + this.rate(value); + }); + + return angular.extend(<Icon>{ + element: iconElm, + index: index, + stateActive: stateActive, + stateHover: stateHover + }, state); + }); + + this.icons.forEach(icon => { + $element.append(icon.element); + }); + + $element + .addClass('ui rating') + .addClass($attrs.type || ratingConfig.type) + .addClass($attrs.size || ratingConfig.size) + .attr({ + 'aria-valuemax': this.icons.length, + 'aria-valuemin': 0, + role: 'slider', + tabindex: 0 + }) + .on('mouseleave', () => { + this.hoverValue = -1; + if (angular.isDefined($attrs.onLeave)) { + $scope.$evalAsync($attrs.onLeave); + } + $element.removeClass(stateHoverParent); + this.updateStateHover(); + }) + .on('keydown', (evt: any) => { + if (/(37|38|39|40)/.test(evt.which)) { + evt.preventDefault(); + evt.stopPropagation(); + this.rate(this.ngModel.$viewValue + (evt.which === 38 || evt.which === 39 ? 1 : -1)); + } + }); + } + + rate(value: number) { + if (!this.readonly && value >= 0 && value <= this.icons.length) { + this.ngModel.$setViewValue(value); + this.ngModel.$render(); + } + } + + init(ngModel: ng.INgModelController) { + this.ngModel = ngModel; + + ngModel.$render = () => { + const value = ngModel.$viewValue; + this.$element.attr('aria-valuenow', value); + + this.icons.forEach((icon: Icon, index) => { + icon.element[index < value ? 'addClass' : 'removeClass'](icon.stateActive); + }); + }; + + ngModel.$formatters.push((value) => { + if (angular.isNumber(value) && value % 1 !== 0) { + value = Math.round(value); + } + return value; + }); + } + + updateStateHover() { + this.icons.forEach((icon: Icon, index) => { + icon.element[index < this.hoverValue ? 'addClass' : 'removeClass'](icon.stateHover); + }); + } + + evalAttribute(attr: string) { + return angular.isDefined(this.$attrs[attr]) ? + this.$scope.$eval(this.$attrs[attr]) : + ratingConfig[attr]; + } +} + +class SmRatingDirective implements ng.IDirective { + static instance(): ng.IDirective { + return new SmRatingDirective; + } + + restrict = 'E'; + require = ['smRating', 'ngModel']; + controller = SmRatingController; + link = ( + scope: ng.IScope, + element: ng.IAugmentedJQuery, + attrs, + ctrls: [SmRatingController, ng.INgModelController] + ) => { + const [smRating, ngModel] = ctrls; + smRating.init(ngModel); + }; +} + +interface Icon extends RatingState { + index: number; + element: ng.IAugmentedJQuery; +} + +interface RatingState { + stateActive: string; + stateHover: string; +} + +export const smRatingModule = angular + .module('semantic.ui.modules.rating', []) + .directive('smRating', SmRatingDirective.instance) + .constant('ratingConfig', ratingConfig);
173
Merge pull request #51 from mxth/rating
0
.ts
ts
mit
Semantic-Org/Semantic-UI-Angular
10072120
<NME> style.css <BEF> html { background: #efefef; font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; font-size: 13px; } body { padding: 0 10px; margin: 10px auto 0; } .header { background: #ededed; background: -webkit-gradient(linear, left top, left bottom, color-stop(0%,#576a76), color-stop(100%,#4d5256)); background: -moz-linear-gradient(top, #576076 0%, #414e58 100%); background: -webkit-linear-gradient(top, #576a76 0%, #414e58 100%); background: -o-linear-gradient(top, #576a76 0%, #414e58 100%); background: -ms-linear-gradient(top, #576a76 0%, #414e58 100%); background: linear-gradient(top, #576a76 0%, #414e58 100%); border-bottom: 1px solid #fff; -moz-border-radius-topleft: 5px; -webkit-border-top-left-radius: 5px; border-top-left-radius: 5px; -moz-border-radius-topright: 5px; -webkit-border-top-right-radius:5px; border-top-right-radius: 5px; overflow:hidden; padding: 10px 5%; text-shadow:0 1px 0 #000; } } .reset{ font-size:10px; line-height:38px; } .header ul li { display: inline; } .header ul li a { color: #eee; text-decoration: none; margin-right: 10px; display: inline-block; padding: 4px 8px; -moz-border-radius: 10px; -webkit-border-radius:10px; border-radius: 10px; } .header ul li a:hover { background: rgba(255,255,255,0.1); } .header ul li a:active { -moz-box-shadow: inset 0 1px 0 rgba(0,0,0,0.2); -webkit-box-shadow:inset 0 1px 0 rgba(0,0,0,0.2); box-shadow: inset 0 1px 0 rgba(0,0,0,0.2); } .header ul li.current a { background: rgba(255,255,255,0.1); -moz-box-shadow: inset 0 1px 0 rgba(0,0,0,0.2); -webkit-box-shadow:inset 0 1px 0 rgba(0,0,0,0.2); box-shadow: inset 0 1px 0 rgba(0,0,0,0.2); color: #fff; } .header p.environment { clear: both; padding: 10px 0 0 0; color: #BBB; font-style: italic; float: right; } #main { padding: 10px 5%; background: #f9f9f9; border:1px solid #ccc; border-top:none; -moz-box-shadow: 0 3px 10px rgba(0,0,0,0.2); -webkit-box-shadow:0 3px 10px rgba(0,0,0,0.2); box-shadow: 0 3px 10px rgba(0,0,0,0.2); overflow: hidden; } #main .logo { float: right; margin: 10px; } #main span.hl { background: #efefef; padding: 2px; } #main h1 { margin: 10px 0; font-size: 190%; font-weight: bold; color: #0080FF; } #main table { width: 100%; margin:0 0 10px; } #main table tr td, #main table tr th { border-bottom: 1px solid #ccc; padding: 6px; } #main table tr th { background: #efefef; color: #888; font-size: 80%; text-transform:uppercase; } #main table tr td.no-data { text-align: center; padding: 40px 0; color: #999; font-style: italic; font-size: 130%; } #main a { color: #111; } #main p { margin: 5px 0; } #main p.intro { margin-bottom: 15px; font-size: 85%; color: #999; margin-top: 0; line-height: 1.3; } #main h1.wi { margin-bottom: 5px; } #main p.sub { font-size: 95%; color: #999; } .experiment { background:#fff; border: 1px solid #eee; border-bottom:none; margin:30px 0; } .experiment_with_goal { margin: -32px 0 30px 0; } .experiment .experiment-header { background: #f4f4f4; background: -webkit-gradient(linear, left top, left bottom, color-stop(0%,#f4f4f4), color-stop(100%,#e0e0e0)); background: -moz-linear-gradient (top, #f4f4f4 0%, #e0e0e0 100%); background: -webkit-linear-gradient(top, #f4f4f4 0%, #e0e0e0 100%); background: -o-linear-gradient (top, #f4f4f4 0%, #e0e0e0 100%); background: -ms-linear-gradient (top, #f4f4f4 0%, #e0e0e0 100%); background: linear-gradient (top, #f4f4f4 0%, #e0e0e0 100%); border-top:1px solid #fff; overflow:hidden; padding:0 10px; } .experiment h2 { color:#888; margin: 12px 0 12px 0; font-size: 1em; font-weight:bold; float:left; text-shadow:0 1px 0 rgba(255,255,255,0.8); } .experiment h2 .goal { font-style: italic; } .experiment h2 .version { font-style:italic; font-size:0.8em; color:#bbb; font-weight:normal; } .experiment table em{ font-style:italic; font-size:0.9em; color:#bbb; } .experiment table .totals td { background: #eee; font-weight: bold; } #footer { padding: 10px 5%; color: #999; font-size: 85%; line-height: 1.5; padding-top: 10px; } #footer p a { color: #999; } .inline-controls { float:right; } .inline-controls small { color: #888; font-size: 11px; } .inline-controls form { display: inline-block; font-size: 10px; line-height: 38px; } .inline-controls input { margin-left: 10px; } .worse, .better { color: #773F3F; font-size: 10px; font-weight:bold; } .better { color: #408C48; } .experiment a.button, .experiment button, .experiment input[type="submit"] { padding: 4px 10px; overflow: hidden; background: #d8dae0; -moz-box-shadow: 0 1px 0 rgba(0,0,0,0.5); -webkit-box-shadow:0 1px 0 rgba(0,0,0,0.5); box-shadow: 0 1px 0 rgba(0,0,0,0.5); border:none; -moz-border-radius: 30px; -webkit-border-radius:30px; border-radius: 30px; color:#2e3035; cursor: pointer; font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; text-decoration: none; text-shadow:0 1px 0 rgba(255,255,255,0.8); -moz-user-select: none; -webkit-user-select:none; user-select: none; white-space: nowrap; } a.button:hover, button:hover, input[type="submit"]:hover, a.button:focus, button:focus, input[type="submit"]:focus{ background:#bbbfc7; } a.button:active, button:active, input[type="submit"]:active{ -moz-box-shadow: inset 0 0 4px #484d57; -webkit-box-shadow:inset 0 0 4px #484d57; box-shadow: inset 0 0 4px #484d57; position:relative; top:1px; } a.button.red, button.red, input[type="submit"].red, a.button.green, button.green, input[type="submit"].green { color:#fff; text-shadow:0 1px 0 rgba(0,0,0,0.4); } a.button.red, button.red, input[type="submit"].red { background:#a56d6d; } a.button.red:hover, button.red:hover, input[type="submit"].red:hover, a.button.red:focus, button.red:focus, input[type="submit"].red:focus { background:#895C5C; } a.button.green, button.green, input[type="submit"].green { background:#8daa92; } a.button.green:hover, button.green:hover, input[type="submit"].green:hover, a.button.green:focus, button.green:focus, input[type="submit"].green:focus { background:#768E7A; } .dashboard-controls input, .dashboard-controls select { padding: 10px; } .dashboard-controls-bottom { margin-top: 10px; } .pagination { text-align: center; font-size: 15px; } .pagination a, .paginaton span { display: inline-block; padding: 5px; } .divider { display: inline-block; margin-left: 10px; } <MSG> no more massive clickable area on the reset button <DFF> @@ -35,6 +35,7 @@ h2{ } .reset{ + display:inline-block; font-size:10px; line-height:38px; }
1
no more massive clickable area on the reset button
0
.css
css
mit
splitrb/split
10072121
<NME> style.css <BEF> html { background: #efefef; font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; font-size: 13px; } body { padding: 0 10px; margin: 10px auto 0; } .header { background: #ededed; background: -webkit-gradient(linear, left top, left bottom, color-stop(0%,#576a76), color-stop(100%,#4d5256)); background: -moz-linear-gradient(top, #576076 0%, #414e58 100%); background: -webkit-linear-gradient(top, #576a76 0%, #414e58 100%); background: -o-linear-gradient(top, #576a76 0%, #414e58 100%); background: -ms-linear-gradient(top, #576a76 0%, #414e58 100%); background: linear-gradient(top, #576a76 0%, #414e58 100%); border-bottom: 1px solid #fff; -moz-border-radius-topleft: 5px; -webkit-border-top-left-radius: 5px; border-top-left-radius: 5px; -moz-border-radius-topright: 5px; -webkit-border-top-right-radius:5px; border-top-right-radius: 5px; overflow:hidden; padding: 10px 5%; text-shadow:0 1px 0 #000; } } .reset{ font-size:10px; line-height:38px; } .header ul li { display: inline; } .header ul li a { color: #eee; text-decoration: none; margin-right: 10px; display: inline-block; padding: 4px 8px; -moz-border-radius: 10px; -webkit-border-radius:10px; border-radius: 10px; } .header ul li a:hover { background: rgba(255,255,255,0.1); } .header ul li a:active { -moz-box-shadow: inset 0 1px 0 rgba(0,0,0,0.2); -webkit-box-shadow:inset 0 1px 0 rgba(0,0,0,0.2); box-shadow: inset 0 1px 0 rgba(0,0,0,0.2); } .header ul li.current a { background: rgba(255,255,255,0.1); -moz-box-shadow: inset 0 1px 0 rgba(0,0,0,0.2); -webkit-box-shadow:inset 0 1px 0 rgba(0,0,0,0.2); box-shadow: inset 0 1px 0 rgba(0,0,0,0.2); color: #fff; } .header p.environment { clear: both; padding: 10px 0 0 0; color: #BBB; font-style: italic; float: right; } #main { padding: 10px 5%; background: #f9f9f9; border:1px solid #ccc; border-top:none; -moz-box-shadow: 0 3px 10px rgba(0,0,0,0.2); -webkit-box-shadow:0 3px 10px rgba(0,0,0,0.2); box-shadow: 0 3px 10px rgba(0,0,0,0.2); overflow: hidden; } #main .logo { float: right; margin: 10px; } #main span.hl { background: #efefef; padding: 2px; } #main h1 { margin: 10px 0; font-size: 190%; font-weight: bold; color: #0080FF; } #main table { width: 100%; margin:0 0 10px; } #main table tr td, #main table tr th { border-bottom: 1px solid #ccc; padding: 6px; } #main table tr th { background: #efefef; color: #888; font-size: 80%; text-transform:uppercase; } #main table tr td.no-data { text-align: center; padding: 40px 0; color: #999; font-style: italic; font-size: 130%; } #main a { color: #111; } #main p { margin: 5px 0; } #main p.intro { margin-bottom: 15px; font-size: 85%; color: #999; margin-top: 0; line-height: 1.3; } #main h1.wi { margin-bottom: 5px; } #main p.sub { font-size: 95%; color: #999; } .experiment { background:#fff; border: 1px solid #eee; border-bottom:none; margin:30px 0; } .experiment_with_goal { margin: -32px 0 30px 0; } .experiment .experiment-header { background: #f4f4f4; background: -webkit-gradient(linear, left top, left bottom, color-stop(0%,#f4f4f4), color-stop(100%,#e0e0e0)); background: -moz-linear-gradient (top, #f4f4f4 0%, #e0e0e0 100%); background: -webkit-linear-gradient(top, #f4f4f4 0%, #e0e0e0 100%); background: -o-linear-gradient (top, #f4f4f4 0%, #e0e0e0 100%); background: -ms-linear-gradient (top, #f4f4f4 0%, #e0e0e0 100%); background: linear-gradient (top, #f4f4f4 0%, #e0e0e0 100%); border-top:1px solid #fff; overflow:hidden; padding:0 10px; } .experiment h2 { color:#888; margin: 12px 0 12px 0; font-size: 1em; font-weight:bold; float:left; text-shadow:0 1px 0 rgba(255,255,255,0.8); } .experiment h2 .goal { font-style: italic; } .experiment h2 .version { font-style:italic; font-size:0.8em; color:#bbb; font-weight:normal; } .experiment table em{ font-style:italic; font-size:0.9em; color:#bbb; } .experiment table .totals td { background: #eee; font-weight: bold; } #footer { padding: 10px 5%; color: #999; font-size: 85%; line-height: 1.5; padding-top: 10px; } #footer p a { color: #999; } .inline-controls { float:right; } .inline-controls small { color: #888; font-size: 11px; } .inline-controls form { display: inline-block; font-size: 10px; line-height: 38px; } .inline-controls input { margin-left: 10px; } .worse, .better { color: #773F3F; font-size: 10px; font-weight:bold; } .better { color: #408C48; } .experiment a.button, .experiment button, .experiment input[type="submit"] { padding: 4px 10px; overflow: hidden; background: #d8dae0; -moz-box-shadow: 0 1px 0 rgba(0,0,0,0.5); -webkit-box-shadow:0 1px 0 rgba(0,0,0,0.5); box-shadow: 0 1px 0 rgba(0,0,0,0.5); border:none; -moz-border-radius: 30px; -webkit-border-radius:30px; border-radius: 30px; color:#2e3035; cursor: pointer; font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; text-decoration: none; text-shadow:0 1px 0 rgba(255,255,255,0.8); -moz-user-select: none; -webkit-user-select:none; user-select: none; white-space: nowrap; } a.button:hover, button:hover, input[type="submit"]:hover, a.button:focus, button:focus, input[type="submit"]:focus{ background:#bbbfc7; } a.button:active, button:active, input[type="submit"]:active{ -moz-box-shadow: inset 0 0 4px #484d57; -webkit-box-shadow:inset 0 0 4px #484d57; box-shadow: inset 0 0 4px #484d57; position:relative; top:1px; } a.button.red, button.red, input[type="submit"].red, a.button.green, button.green, input[type="submit"].green { color:#fff; text-shadow:0 1px 0 rgba(0,0,0,0.4); } a.button.red, button.red, input[type="submit"].red { background:#a56d6d; } a.button.red:hover, button.red:hover, input[type="submit"].red:hover, a.button.red:focus, button.red:focus, input[type="submit"].red:focus { background:#895C5C; } a.button.green, button.green, input[type="submit"].green { background:#8daa92; } a.button.green:hover, button.green:hover, input[type="submit"].green:hover, a.button.green:focus, button.green:focus, input[type="submit"].green:focus { background:#768E7A; } .dashboard-controls input, .dashboard-controls select { padding: 10px; } .dashboard-controls-bottom { margin-top: 10px; } .pagination { text-align: center; font-size: 15px; } .pagination a, .paginaton span { display: inline-block; padding: 5px; } .divider { display: inline-block; margin-left: 10px; } <MSG> no more massive clickable area on the reset button <DFF> @@ -35,6 +35,7 @@ h2{ } .reset{ + display:inline-block; font-size:10px; line-height:38px; }
1
no more massive clickable area on the reset button
0
.css
css
mit
splitrb/split
10072122
<NME> style.css <BEF> html { background: #efefef; font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; font-size: 13px; } body { padding: 0 10px; margin: 10px auto 0; } .header { background: #ededed; background: -webkit-gradient(linear, left top, left bottom, color-stop(0%,#576a76), color-stop(100%,#4d5256)); background: -moz-linear-gradient(top, #576076 0%, #414e58 100%); background: -webkit-linear-gradient(top, #576a76 0%, #414e58 100%); background: -o-linear-gradient(top, #576a76 0%, #414e58 100%); background: -ms-linear-gradient(top, #576a76 0%, #414e58 100%); background: linear-gradient(top, #576a76 0%, #414e58 100%); border-bottom: 1px solid #fff; -moz-border-radius-topleft: 5px; -webkit-border-top-left-radius: 5px; border-top-left-radius: 5px; -moz-border-radius-topright: 5px; -webkit-border-top-right-radius:5px; border-top-right-radius: 5px; overflow:hidden; padding: 10px 5%; text-shadow:0 1px 0 #000; } } .reset{ font-size:10px; line-height:38px; } .header ul li { display: inline; } .header ul li a { color: #eee; text-decoration: none; margin-right: 10px; display: inline-block; padding: 4px 8px; -moz-border-radius: 10px; -webkit-border-radius:10px; border-radius: 10px; } .header ul li a:hover { background: rgba(255,255,255,0.1); } .header ul li a:active { -moz-box-shadow: inset 0 1px 0 rgba(0,0,0,0.2); -webkit-box-shadow:inset 0 1px 0 rgba(0,0,0,0.2); box-shadow: inset 0 1px 0 rgba(0,0,0,0.2); } .header ul li.current a { background: rgba(255,255,255,0.1); -moz-box-shadow: inset 0 1px 0 rgba(0,0,0,0.2); -webkit-box-shadow:inset 0 1px 0 rgba(0,0,0,0.2); box-shadow: inset 0 1px 0 rgba(0,0,0,0.2); color: #fff; } .header p.environment { clear: both; padding: 10px 0 0 0; color: #BBB; font-style: italic; float: right; } #main { padding: 10px 5%; background: #f9f9f9; border:1px solid #ccc; border-top:none; -moz-box-shadow: 0 3px 10px rgba(0,0,0,0.2); -webkit-box-shadow:0 3px 10px rgba(0,0,0,0.2); box-shadow: 0 3px 10px rgba(0,0,0,0.2); overflow: hidden; } #main .logo { float: right; margin: 10px; } #main span.hl { background: #efefef; padding: 2px; } #main h1 { margin: 10px 0; font-size: 190%; font-weight: bold; color: #0080FF; } #main table { width: 100%; margin:0 0 10px; } #main table tr td, #main table tr th { border-bottom: 1px solid #ccc; padding: 6px; } #main table tr th { background: #efefef; color: #888; font-size: 80%; text-transform:uppercase; } #main table tr td.no-data { text-align: center; padding: 40px 0; color: #999; font-style: italic; font-size: 130%; } #main a { color: #111; } #main p { margin: 5px 0; } #main p.intro { margin-bottom: 15px; font-size: 85%; color: #999; margin-top: 0; line-height: 1.3; } #main h1.wi { margin-bottom: 5px; } #main p.sub { font-size: 95%; color: #999; } .experiment { background:#fff; border: 1px solid #eee; border-bottom:none; margin:30px 0; } .experiment_with_goal { margin: -32px 0 30px 0; } .experiment .experiment-header { background: #f4f4f4; background: -webkit-gradient(linear, left top, left bottom, color-stop(0%,#f4f4f4), color-stop(100%,#e0e0e0)); background: -moz-linear-gradient (top, #f4f4f4 0%, #e0e0e0 100%); background: -webkit-linear-gradient(top, #f4f4f4 0%, #e0e0e0 100%); background: -o-linear-gradient (top, #f4f4f4 0%, #e0e0e0 100%); background: -ms-linear-gradient (top, #f4f4f4 0%, #e0e0e0 100%); background: linear-gradient (top, #f4f4f4 0%, #e0e0e0 100%); border-top:1px solid #fff; overflow:hidden; padding:0 10px; } .experiment h2 { color:#888; margin: 12px 0 12px 0; font-size: 1em; font-weight:bold; float:left; text-shadow:0 1px 0 rgba(255,255,255,0.8); } .experiment h2 .goal { font-style: italic; } .experiment h2 .version { font-style:italic; font-size:0.8em; color:#bbb; font-weight:normal; } .experiment table em{ font-style:italic; font-size:0.9em; color:#bbb; } .experiment table .totals td { background: #eee; font-weight: bold; } #footer { padding: 10px 5%; color: #999; font-size: 85%; line-height: 1.5; padding-top: 10px; } #footer p a { color: #999; } .inline-controls { float:right; } .inline-controls small { color: #888; font-size: 11px; } .inline-controls form { display: inline-block; font-size: 10px; line-height: 38px; } .inline-controls input { margin-left: 10px; } .worse, .better { color: #773F3F; font-size: 10px; font-weight:bold; } .better { color: #408C48; } .experiment a.button, .experiment button, .experiment input[type="submit"] { padding: 4px 10px; overflow: hidden; background: #d8dae0; -moz-box-shadow: 0 1px 0 rgba(0,0,0,0.5); -webkit-box-shadow:0 1px 0 rgba(0,0,0,0.5); box-shadow: 0 1px 0 rgba(0,0,0,0.5); border:none; -moz-border-radius: 30px; -webkit-border-radius:30px; border-radius: 30px; color:#2e3035; cursor: pointer; font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; text-decoration: none; text-shadow:0 1px 0 rgba(255,255,255,0.8); -moz-user-select: none; -webkit-user-select:none; user-select: none; white-space: nowrap; } a.button:hover, button:hover, input[type="submit"]:hover, a.button:focus, button:focus, input[type="submit"]:focus{ background:#bbbfc7; } a.button:active, button:active, input[type="submit"]:active{ -moz-box-shadow: inset 0 0 4px #484d57; -webkit-box-shadow:inset 0 0 4px #484d57; box-shadow: inset 0 0 4px #484d57; position:relative; top:1px; } a.button.red, button.red, input[type="submit"].red, a.button.green, button.green, input[type="submit"].green { color:#fff; text-shadow:0 1px 0 rgba(0,0,0,0.4); } a.button.red, button.red, input[type="submit"].red { background:#a56d6d; } a.button.red:hover, button.red:hover, input[type="submit"].red:hover, a.button.red:focus, button.red:focus, input[type="submit"].red:focus { background:#895C5C; } a.button.green, button.green, input[type="submit"].green { background:#8daa92; } a.button.green:hover, button.green:hover, input[type="submit"].green:hover, a.button.green:focus, button.green:focus, input[type="submit"].green:focus { background:#768E7A; } .dashboard-controls input, .dashboard-controls select { padding: 10px; } .dashboard-controls-bottom { margin-top: 10px; } .pagination { text-align: center; font-size: 15px; } .pagination a, .paginaton span { display: inline-block; padding: 5px; } .divider { display: inline-block; margin-left: 10px; } <MSG> no more massive clickable area on the reset button <DFF> @@ -35,6 +35,7 @@ h2{ } .reset{ + display:inline-block; font-size:10px; line-height:38px; }
1
no more massive clickable area on the reset button
0
.css
css
mit
splitrb/split
10072123
<NME> .jscsrc <BEF> { "requireCurlyBraces": [ "if", "else", "for", "while", "do", "try", "catch" ], "requireSpaceAfterKeywords": [ "if", "else", "for", "while", "do", "switch", "case", "return", "try", "catch", "typeof" ], "requireSpaceBeforeBinaryOperators": [ "=", "+=", "-=", "*=", "/=", "%=", "<<=", ">>=", ">>>=", "&=", "|=", "^=", "+=", "+", "-", "*", "/", "%", "<<", ">>", ">>>", "&", "|", "^", "&&", "||", "===", "==", ">=", "<=", "<", ">", "!=", "!==" ], "requireSpaceBeforeBlockStatements": true, "requireParenthesesAroundIIFE": true, "requireSpacesInConditionalExpression": true, "disallowSpacesInNamedFunctionExpression": { "beforeOpeningRoundBrace": true }, "disallowSpacesInFunctionDeclaration": { "beforeOpeningRoundBrace": true }, "requireBlocksOnNewline": 1, "disallowEmptyBlocks": true, "disallowSpacesInsideArrayBrackets": true, "disallowSpacesInsideParentheses": true, "disallowSpaceAfterObjectKeys": true, "requireCommaBeforeLineBreak": true, "disallowSpaceAfterPrefixUnaryOperators": true, "disallowSpaceBeforePostfixUnaryOperators": true, "disallowSpaceBeforeBinaryOperators": [ "," ], "requireSpaceBeforeBinaryOperators": true, "requireSpaceAfterBinaryOperators": true, "disallowKeywords": [ "with" ], "disallowMultipleLineBreaks": true, "validateLineBreaks": "LF", "validateQuoteMarks": true, "validateIndentation": 2, "disallowMixedSpacesAndTabs": true, "disallowTrailingWhitespace": true, "disallowTrailingComma": true, "disallowKeywordsOnNewLine": [ "else" ], "requireLineFeedAtFileEnd": true, "requireCapitalizedConstructors": true, "requireDotNotation": true, "disallowYodaConditions": true, "requireSpacesInFunctionExpression": { "beforeOpeningCurlyBrace": true }, "disallowSpacesInFunctionExpression": { "beforeOpeningRoundBrace": true }, "disallowSpaceAfterObjectKeys": true, "requireSpaceBeforeObjectValues": true } <MSG> chore(.jsscrc) Updated jssc to use rules as for angularjs <DFF> @@ -1,75 +1,40 @@ { - "requireCurlyBraces": [ - "if", - "else", - "for", - "while", - "do", - "try", - "catch" - ], - "requireSpaceAfterKeywords": [ - "if", - "else", - "for", - "while", - "do", - "switch", - "case", - "return", - "try", - "catch", - "typeof" - ], - "requireSpaceBeforeBinaryOperators": [ - "=", "+=", "-=", "*=", "/=", "%=", "<<=", ">>=", ">>>=", - "&=", "|=", "^=", "+=", - - "+", "-", "*", "/", "%", "<<", ">>", ">>>", "&", - "|", "^", "&&", "||", "===", "==", ">=", - "<=", "<", ">", "!=", "!==" - ], - "requireSpaceBeforeBlockStatements": true, - "requireParenthesesAroundIIFE": true, - "requireSpacesInConditionalExpression": true, - "disallowSpacesInNamedFunctionExpression": { + "disallowKeywords": ["with"], + "disallowMixedSpacesAndTabs": true, + "disallowMultipleLineStrings": true, + "disallowNewlineBeforeBlockStatements": true, + "disallowSpaceAfterObjectKeys": true, + "disallowSpaceAfterPrefixUnaryOperators": ["++", "--", "+", "-", "~", "!"], + "disallowSpaceBeforeBinaryOperators": [","], + "disallowSpaceBeforePostfixUnaryOperators": ["++", "--"], + "disallowSpacesInAnonymousFunctionExpression": { "beforeOpeningRoundBrace": true }, "disallowSpacesInFunctionDeclaration": { "beforeOpeningRoundBrace": true }, - "requireBlocksOnNewline": 1, - "disallowEmptyBlocks": true, + "disallowSpacesInNamedFunctionExpression": { + "beforeOpeningRoundBrace": true + }, "disallowSpacesInsideArrayBrackets": true, "disallowSpacesInsideParentheses": true, - "disallowSpaceAfterObjectKeys": true, - "requireCommaBeforeLineBreak": true, - "disallowSpaceAfterPrefixUnaryOperators": true, - "disallowSpaceBeforePostfixUnaryOperators": true, - "disallowSpaceBeforeBinaryOperators": [ - "," - ], - "requireSpaceBeforeBinaryOperators": true, - "requireSpaceAfterBinaryOperators": true, - "disallowKeywords": [ "with" ], - "disallowMultipleLineBreaks": true, - "validateLineBreaks": "LF", - "validateQuoteMarks": true, - "validateIndentation": 2, - "disallowMixedSpacesAndTabs": true, - "disallowTrailingWhitespace": true, "disallowTrailingComma": true, - "disallowKeywordsOnNewLine": [ "else" ], + "disallowTrailingWhitespace": true, + "requireCommaBeforeLineBreak": true, "requireLineFeedAtFileEnd": true, - "requireCapitalizedConstructors": true, - "requireDotNotation": true, - "disallowYodaConditions": true, - "requireSpacesInFunctionExpression": { - "beforeOpeningCurlyBrace": true + "requireSpaceAfterBinaryOperators": ["?", ":", "+", "-", "/", "*", "%", "==", "===", "!=", "!==", ">", ">=", "<", "<=", "&&", "||"], + "requireSpaceBeforeBinaryOperators": ["?", ":", "+", "-", "/", "*", "%", "==", "===", "!=", "!==", ">", ">=", "<", "<=", "&&", "||"], + "requireSpaceAfterKeywords": ["if", "else", "for", "while", "do", "switch", "return", "try", "catch"], + "requireSpaceBeforeBlockStatements": true, + "requireSpacesInConditionalExpression": { + "afterTest": true, + "beforeConsequent": true, + "afterConsequent": true, + "beforeAlternate": true }, - "disallowSpacesInFunctionExpression": { - "beforeOpeningRoundBrace": true + "requireSpacesInFunction": { + "beforeOpeningCurlyBrace": true }, - "disallowSpaceAfterObjectKeys": true, - "requireSpaceBeforeObjectValues": true -} \ No newline at end of file + "validateLineBreaks": "LF", + "validateParameterSeparator": ", " +}
28
chore(.jsscrc) Updated jssc to use rules as for angularjs
63
jscsrc
mit
Semantic-Org/Semantic-UI-Angular
10072124
<NME> .jscsrc <BEF> { "requireCurlyBraces": [ "if", "else", "for", "while", "do", "try", "catch" ], "requireSpaceAfterKeywords": [ "if", "else", "for", "while", "do", "switch", "case", "return", "try", "catch", "typeof" ], "requireSpaceBeforeBinaryOperators": [ "=", "+=", "-=", "*=", "/=", "%=", "<<=", ">>=", ">>>=", "&=", "|=", "^=", "+=", "+", "-", "*", "/", "%", "<<", ">>", ">>>", "&", "|", "^", "&&", "||", "===", "==", ">=", "<=", "<", ">", "!=", "!==" ], "requireSpaceBeforeBlockStatements": true, "requireParenthesesAroundIIFE": true, "requireSpacesInConditionalExpression": true, "disallowSpacesInNamedFunctionExpression": { "beforeOpeningRoundBrace": true }, "disallowSpacesInFunctionDeclaration": { "beforeOpeningRoundBrace": true }, "requireBlocksOnNewline": 1, "disallowEmptyBlocks": true, "disallowSpacesInsideArrayBrackets": true, "disallowSpacesInsideParentheses": true, "disallowSpaceAfterObjectKeys": true, "requireCommaBeforeLineBreak": true, "disallowSpaceAfterPrefixUnaryOperators": true, "disallowSpaceBeforePostfixUnaryOperators": true, "disallowSpaceBeforeBinaryOperators": [ "," ], "requireSpaceBeforeBinaryOperators": true, "requireSpaceAfterBinaryOperators": true, "disallowKeywords": [ "with" ], "disallowMultipleLineBreaks": true, "validateLineBreaks": "LF", "validateQuoteMarks": true, "validateIndentation": 2, "disallowMixedSpacesAndTabs": true, "disallowTrailingWhitespace": true, "disallowTrailingComma": true, "disallowKeywordsOnNewLine": [ "else" ], "requireLineFeedAtFileEnd": true, "requireCapitalizedConstructors": true, "requireDotNotation": true, "disallowYodaConditions": true, "requireSpacesInFunctionExpression": { "beforeOpeningCurlyBrace": true }, "disallowSpacesInFunctionExpression": { "beforeOpeningRoundBrace": true }, "disallowSpaceAfterObjectKeys": true, "requireSpaceBeforeObjectValues": true } <MSG> chore(.jsscrc) Updated jssc to use rules as for angularjs <DFF> @@ -1,75 +1,40 @@ { - "requireCurlyBraces": [ - "if", - "else", - "for", - "while", - "do", - "try", - "catch" - ], - "requireSpaceAfterKeywords": [ - "if", - "else", - "for", - "while", - "do", - "switch", - "case", - "return", - "try", - "catch", - "typeof" - ], - "requireSpaceBeforeBinaryOperators": [ - "=", "+=", "-=", "*=", "/=", "%=", "<<=", ">>=", ">>>=", - "&=", "|=", "^=", "+=", - - "+", "-", "*", "/", "%", "<<", ">>", ">>>", "&", - "|", "^", "&&", "||", "===", "==", ">=", - "<=", "<", ">", "!=", "!==" - ], - "requireSpaceBeforeBlockStatements": true, - "requireParenthesesAroundIIFE": true, - "requireSpacesInConditionalExpression": true, - "disallowSpacesInNamedFunctionExpression": { + "disallowKeywords": ["with"], + "disallowMixedSpacesAndTabs": true, + "disallowMultipleLineStrings": true, + "disallowNewlineBeforeBlockStatements": true, + "disallowSpaceAfterObjectKeys": true, + "disallowSpaceAfterPrefixUnaryOperators": ["++", "--", "+", "-", "~", "!"], + "disallowSpaceBeforeBinaryOperators": [","], + "disallowSpaceBeforePostfixUnaryOperators": ["++", "--"], + "disallowSpacesInAnonymousFunctionExpression": { "beforeOpeningRoundBrace": true }, "disallowSpacesInFunctionDeclaration": { "beforeOpeningRoundBrace": true }, - "requireBlocksOnNewline": 1, - "disallowEmptyBlocks": true, + "disallowSpacesInNamedFunctionExpression": { + "beforeOpeningRoundBrace": true + }, "disallowSpacesInsideArrayBrackets": true, "disallowSpacesInsideParentheses": true, - "disallowSpaceAfterObjectKeys": true, - "requireCommaBeforeLineBreak": true, - "disallowSpaceAfterPrefixUnaryOperators": true, - "disallowSpaceBeforePostfixUnaryOperators": true, - "disallowSpaceBeforeBinaryOperators": [ - "," - ], - "requireSpaceBeforeBinaryOperators": true, - "requireSpaceAfterBinaryOperators": true, - "disallowKeywords": [ "with" ], - "disallowMultipleLineBreaks": true, - "validateLineBreaks": "LF", - "validateQuoteMarks": true, - "validateIndentation": 2, - "disallowMixedSpacesAndTabs": true, - "disallowTrailingWhitespace": true, "disallowTrailingComma": true, - "disallowKeywordsOnNewLine": [ "else" ], + "disallowTrailingWhitespace": true, + "requireCommaBeforeLineBreak": true, "requireLineFeedAtFileEnd": true, - "requireCapitalizedConstructors": true, - "requireDotNotation": true, - "disallowYodaConditions": true, - "requireSpacesInFunctionExpression": { - "beforeOpeningCurlyBrace": true + "requireSpaceAfterBinaryOperators": ["?", ":", "+", "-", "/", "*", "%", "==", "===", "!=", "!==", ">", ">=", "<", "<=", "&&", "||"], + "requireSpaceBeforeBinaryOperators": ["?", ":", "+", "-", "/", "*", "%", "==", "===", "!=", "!==", ">", ">=", "<", "<=", "&&", "||"], + "requireSpaceAfterKeywords": ["if", "else", "for", "while", "do", "switch", "return", "try", "catch"], + "requireSpaceBeforeBlockStatements": true, + "requireSpacesInConditionalExpression": { + "afterTest": true, + "beforeConsequent": true, + "afterConsequent": true, + "beforeAlternate": true }, - "disallowSpacesInFunctionExpression": { - "beforeOpeningRoundBrace": true + "requireSpacesInFunction": { + "beforeOpeningCurlyBrace": true }, - "disallowSpaceAfterObjectKeys": true, - "requireSpaceBeforeObjectValues": true -} \ No newline at end of file + "validateLineBreaks": "LF", + "validateParameterSeparator": ", " +}
28
chore(.jsscrc) Updated jssc to use rules as for angularjs
63
jscsrc
mit
Semantic-Org/Semantic-UI-Angular
10072125
<NME> .jscsrc <BEF> { "requireCurlyBraces": [ "if", "else", "for", "while", "do", "try", "catch" ], "requireSpaceAfterKeywords": [ "if", "else", "for", "while", "do", "switch", "case", "return", "try", "catch", "typeof" ], "requireSpaceBeforeBinaryOperators": [ "=", "+=", "-=", "*=", "/=", "%=", "<<=", ">>=", ">>>=", "&=", "|=", "^=", "+=", "+", "-", "*", "/", "%", "<<", ">>", ">>>", "&", "|", "^", "&&", "||", "===", "==", ">=", "<=", "<", ">", "!=", "!==" ], "requireSpaceBeforeBlockStatements": true, "requireParenthesesAroundIIFE": true, "requireSpacesInConditionalExpression": true, "disallowSpacesInNamedFunctionExpression": { "beforeOpeningRoundBrace": true }, "disallowSpacesInFunctionDeclaration": { "beforeOpeningRoundBrace": true }, "requireBlocksOnNewline": 1, "disallowEmptyBlocks": true, "disallowSpacesInsideArrayBrackets": true, "disallowSpacesInsideParentheses": true, "disallowSpaceAfterObjectKeys": true, "requireCommaBeforeLineBreak": true, "disallowSpaceAfterPrefixUnaryOperators": true, "disallowSpaceBeforePostfixUnaryOperators": true, "disallowSpaceBeforeBinaryOperators": [ "," ], "requireSpaceBeforeBinaryOperators": true, "requireSpaceAfterBinaryOperators": true, "disallowKeywords": [ "with" ], "disallowMultipleLineBreaks": true, "validateLineBreaks": "LF", "validateQuoteMarks": true, "validateIndentation": 2, "disallowMixedSpacesAndTabs": true, "disallowTrailingWhitespace": true, "disallowTrailingComma": true, "disallowKeywordsOnNewLine": [ "else" ], "requireLineFeedAtFileEnd": true, "requireCapitalizedConstructors": true, "requireDotNotation": true, "disallowYodaConditions": true, "requireSpacesInFunctionExpression": { "beforeOpeningCurlyBrace": true }, "disallowSpacesInFunctionExpression": { "beforeOpeningRoundBrace": true }, "disallowSpaceAfterObjectKeys": true, "requireSpaceBeforeObjectValues": true } <MSG> chore(.jsscrc) Updated jssc to use rules as for angularjs <DFF> @@ -1,75 +1,40 @@ { - "requireCurlyBraces": [ - "if", - "else", - "for", - "while", - "do", - "try", - "catch" - ], - "requireSpaceAfterKeywords": [ - "if", - "else", - "for", - "while", - "do", - "switch", - "case", - "return", - "try", - "catch", - "typeof" - ], - "requireSpaceBeforeBinaryOperators": [ - "=", "+=", "-=", "*=", "/=", "%=", "<<=", ">>=", ">>>=", - "&=", "|=", "^=", "+=", - - "+", "-", "*", "/", "%", "<<", ">>", ">>>", "&", - "|", "^", "&&", "||", "===", "==", ">=", - "<=", "<", ">", "!=", "!==" - ], - "requireSpaceBeforeBlockStatements": true, - "requireParenthesesAroundIIFE": true, - "requireSpacesInConditionalExpression": true, - "disallowSpacesInNamedFunctionExpression": { + "disallowKeywords": ["with"], + "disallowMixedSpacesAndTabs": true, + "disallowMultipleLineStrings": true, + "disallowNewlineBeforeBlockStatements": true, + "disallowSpaceAfterObjectKeys": true, + "disallowSpaceAfterPrefixUnaryOperators": ["++", "--", "+", "-", "~", "!"], + "disallowSpaceBeforeBinaryOperators": [","], + "disallowSpaceBeforePostfixUnaryOperators": ["++", "--"], + "disallowSpacesInAnonymousFunctionExpression": { "beforeOpeningRoundBrace": true }, "disallowSpacesInFunctionDeclaration": { "beforeOpeningRoundBrace": true }, - "requireBlocksOnNewline": 1, - "disallowEmptyBlocks": true, + "disallowSpacesInNamedFunctionExpression": { + "beforeOpeningRoundBrace": true + }, "disallowSpacesInsideArrayBrackets": true, "disallowSpacesInsideParentheses": true, - "disallowSpaceAfterObjectKeys": true, - "requireCommaBeforeLineBreak": true, - "disallowSpaceAfterPrefixUnaryOperators": true, - "disallowSpaceBeforePostfixUnaryOperators": true, - "disallowSpaceBeforeBinaryOperators": [ - "," - ], - "requireSpaceBeforeBinaryOperators": true, - "requireSpaceAfterBinaryOperators": true, - "disallowKeywords": [ "with" ], - "disallowMultipleLineBreaks": true, - "validateLineBreaks": "LF", - "validateQuoteMarks": true, - "validateIndentation": 2, - "disallowMixedSpacesAndTabs": true, - "disallowTrailingWhitespace": true, "disallowTrailingComma": true, - "disallowKeywordsOnNewLine": [ "else" ], + "disallowTrailingWhitespace": true, + "requireCommaBeforeLineBreak": true, "requireLineFeedAtFileEnd": true, - "requireCapitalizedConstructors": true, - "requireDotNotation": true, - "disallowYodaConditions": true, - "requireSpacesInFunctionExpression": { - "beforeOpeningCurlyBrace": true + "requireSpaceAfterBinaryOperators": ["?", ":", "+", "-", "/", "*", "%", "==", "===", "!=", "!==", ">", ">=", "<", "<=", "&&", "||"], + "requireSpaceBeforeBinaryOperators": ["?", ":", "+", "-", "/", "*", "%", "==", "===", "!=", "!==", ">", ">=", "<", "<=", "&&", "||"], + "requireSpaceAfterKeywords": ["if", "else", "for", "while", "do", "switch", "return", "try", "catch"], + "requireSpaceBeforeBlockStatements": true, + "requireSpacesInConditionalExpression": { + "afterTest": true, + "beforeConsequent": true, + "afterConsequent": true, + "beforeAlternate": true }, - "disallowSpacesInFunctionExpression": { - "beforeOpeningRoundBrace": true + "requireSpacesInFunction": { + "beforeOpeningCurlyBrace": true }, - "disallowSpaceAfterObjectKeys": true, - "requireSpaceBeforeObjectValues": true -} \ No newline at end of file + "validateLineBreaks": "LF", + "validateParameterSeparator": ", " +}
28
chore(.jsscrc) Updated jssc to use rules as for angularjs
63
jscsrc
mit
Semantic-Org/Semantic-UI-Angular
10072126
<NME> buildout.cfg <BEF> [buildout] parts = django find-links = http://bitbucket.org/ubernostrum/django-registration/downloads/django-registration-0.8-alpha-1.tar.gz unzip = true eggs = pkginfo django-registration==0.8-alpha-1 [django] recipe = djangorecipe version = 1.1.1 settings = settings eggs = ${buildout:eggs} test = djangopypi project = chishop wsgi = true <MSG> Use development settings by default <DFF> @@ -8,7 +8,7 @@ eggs = pkginfo [django] recipe = djangorecipe version = 1.1.1 -settings = settings +settings = development eggs = ${buildout:eggs} test = djangopypi project = chishop
1
Use development settings by default
1
.cfg
cfg
bsd-3-clause
ask/chishop
10072127
<NME> extract-abbreviation.ts <BEF> ADDFILE <MSG> Unit tests and docs for abbreviation extractor <DFF> @@ -0,0 +1,126 @@ +import { deepStrictEqual, strictEqual, ok } from 'assert'; +import extractAbbreviation, { ExtractOptions, ExtractedAbbreviation } from '../src/extract-abbreviation'; +import isAtHTMLTag from '../src/extract-abbreviation/is-html'; +import scanner from '../src/extract-abbreviation/reader'; +import { consumeQuoted } from '../src/extract-abbreviation/quotes'; + +function extract(abbr: string, options?: Partial<ExtractOptions>) { + let caretPos: number | undefined = abbr.indexOf('|'); + if (caretPos !== -1) { + abbr = abbr.slice(0, caretPos) + abbr.slice(caretPos + 1); + } else { + caretPos = void 0; + } + + return extractAbbreviation(abbr, caretPos, options); +} + +function result(abbreviation: string, location: number, start = location): ExtractedAbbreviation { + return { + abbreviation, + location, + start: start != null ? start : location, + end: location + abbreviation.length + }; +} + +describe('Extract abbreviation', () => { + it('basic', () => { + deepStrictEqual(extract('.bar'), result('.bar', 0)); + deepStrictEqual(extract('.foo .bar'), result('.bar', 5)); + deepStrictEqual(extract('.foo @bar'), result('@bar', 5)); + deepStrictEqual(extract('.foo img/'), result('img/', 5)); + deepStrictEqual(extract('текстdiv'), result('div', 5)); + deepStrictEqual(extract('foo div[foo="текст" bar=текст2]'), result('div[foo="текст" bar=текст2]', 4)); + }); + + it('abbreviation with operators', () => { + deepStrictEqual(extract('a foo+bar.baz'), result('foo+bar.baz', 2)); + deepStrictEqual(extract('a foo>bar+baz*3'), result('foo>bar+baz*3', 2)); + }); + + it('abbreviation with attributes', () => { + deepStrictEqual(extract('a foo[bar|]'), result('foo[bar]', 2)); + deepStrictEqual(extract('a foo[bar="baz" a b]'), result('foo[bar="baz" a b]', 2)); + deepStrictEqual(extract('foo bar[a|] baz'), result('bar[a]', 4)); + }); + + it('tag test', () => { + deepStrictEqual(extract('<foo>bar[a b="c"]>baz'), result('bar[a b="c"]>baz', 5)); + deepStrictEqual(extract('foo>bar'), result('foo>bar', 0)); + deepStrictEqual(extract('<foo>bar'), result('bar', 5)); + deepStrictEqual(extract('<foo>bar[a="d" b="c"]>baz'), result('bar[a="d" b="c"]>baz', 5)); + }); + + it('stylesheet abbreviation', () => { + deepStrictEqual(extract('foo{bar|}'), result('foo{bar}', 0)); + deepStrictEqual(extract('foo{bar|}', { type: 'stylesheet' }), result('bar', 4)); + }); + + it('prefixed extract', () => { + deepStrictEqual(extract('<foo>bar[a b="c"]>baz'), result('bar[a b="c"]>baz', 5)); + deepStrictEqual(extract('<foo>bar[a b="c"]>baz', { prefix: '<' }), result('foo>bar[a b="c"]>baz', 1, 0)); + deepStrictEqual(extract('<foo>bar[a b="<"]>baz', { prefix: '<' }), result('foo>bar[a b="<"]>baz', 1, 0)); + deepStrictEqual(extract('<foo>bar{<}>baz', { prefix: '<' }), result('foo>bar{<}>baz', 1, 0)); + + // Multiple prefix characters + deepStrictEqual(extract('foo>>>bar[a b="c"]>baz', { prefix: '>>>' }), result('bar[a b="c"]>baz', 6, 3)); + + // Absent prefix + strictEqual(extract('<foo>bar[a b="c"]>baz', { prefix: '&&' }), void 0); + }); + + it('HTML test', () => { + const html = (str: string) => isAtHTMLTag(scanner(str)); + + // simple tag + ok(html('<div>')); + ok(html('<div/>')); + ok(html('<div />')); + ok(html('</div>')); + + // tag with attributes + ok(html('<div foo="bar">')); + ok(html('<div foo=bar>')); + ok(html('<div foo>')); + ok(html('<div a="b" c=d>')); + ok(html('<div a=b c=d>')); + ok(html('<div a=^b$ c=d>')); + ok(html('<div a=b c=^%d]$>')); + ok(html('<div title=привет>')); + ok(html('<div title=привет123>')); + ok(html('<foo-bar>')); + + // invalid tags + ok(!html('div>')); + ok(!html('<div')); + ok(!html('<div привет>')); + ok(!html('<div =bar>')); + ok(!html('<div foo=>')); + ok(!html('[a=b c=d]>')); + ok(!html('div[a=b c=d]>')); + }); + + it('consume quotes', () => { + let s = scanner(' "foo"'); + ok(consumeQuoted(s)); + strictEqual(s.pos, 1); + + s = scanner('"foo"'); + ok(consumeQuoted(s)); + strictEqual(s.pos, 0); + + s = scanner('""'); + ok(consumeQuoted(s)); + strictEqual(s.pos, 0); + + s = scanner('"a\\\"b"'); + ok(consumeQuoted(s)); + strictEqual(s.pos, 0); + + // don’t eat anything + s = scanner('foo'); + ok(!consumeQuoted(s)); + strictEqual(s.pos, 3); + }); +});
126
Unit tests and docs for abbreviation extractor
0
.ts
ts
mit
emmetio/emmet
10072128
<NME> extract-abbreviation.ts <BEF> ADDFILE <MSG> Unit tests and docs for abbreviation extractor <DFF> @@ -0,0 +1,126 @@ +import { deepStrictEqual, strictEqual, ok } from 'assert'; +import extractAbbreviation, { ExtractOptions, ExtractedAbbreviation } from '../src/extract-abbreviation'; +import isAtHTMLTag from '../src/extract-abbreviation/is-html'; +import scanner from '../src/extract-abbreviation/reader'; +import { consumeQuoted } from '../src/extract-abbreviation/quotes'; + +function extract(abbr: string, options?: Partial<ExtractOptions>) { + let caretPos: number | undefined = abbr.indexOf('|'); + if (caretPos !== -1) { + abbr = abbr.slice(0, caretPos) + abbr.slice(caretPos + 1); + } else { + caretPos = void 0; + } + + return extractAbbreviation(abbr, caretPos, options); +} + +function result(abbreviation: string, location: number, start = location): ExtractedAbbreviation { + return { + abbreviation, + location, + start: start != null ? start : location, + end: location + abbreviation.length + }; +} + +describe('Extract abbreviation', () => { + it('basic', () => { + deepStrictEqual(extract('.bar'), result('.bar', 0)); + deepStrictEqual(extract('.foo .bar'), result('.bar', 5)); + deepStrictEqual(extract('.foo @bar'), result('@bar', 5)); + deepStrictEqual(extract('.foo img/'), result('img/', 5)); + deepStrictEqual(extract('текстdiv'), result('div', 5)); + deepStrictEqual(extract('foo div[foo="текст" bar=текст2]'), result('div[foo="текст" bar=текст2]', 4)); + }); + + it('abbreviation with operators', () => { + deepStrictEqual(extract('a foo+bar.baz'), result('foo+bar.baz', 2)); + deepStrictEqual(extract('a foo>bar+baz*3'), result('foo>bar+baz*3', 2)); + }); + + it('abbreviation with attributes', () => { + deepStrictEqual(extract('a foo[bar|]'), result('foo[bar]', 2)); + deepStrictEqual(extract('a foo[bar="baz" a b]'), result('foo[bar="baz" a b]', 2)); + deepStrictEqual(extract('foo bar[a|] baz'), result('bar[a]', 4)); + }); + + it('tag test', () => { + deepStrictEqual(extract('<foo>bar[a b="c"]>baz'), result('bar[a b="c"]>baz', 5)); + deepStrictEqual(extract('foo>bar'), result('foo>bar', 0)); + deepStrictEqual(extract('<foo>bar'), result('bar', 5)); + deepStrictEqual(extract('<foo>bar[a="d" b="c"]>baz'), result('bar[a="d" b="c"]>baz', 5)); + }); + + it('stylesheet abbreviation', () => { + deepStrictEqual(extract('foo{bar|}'), result('foo{bar}', 0)); + deepStrictEqual(extract('foo{bar|}', { type: 'stylesheet' }), result('bar', 4)); + }); + + it('prefixed extract', () => { + deepStrictEqual(extract('<foo>bar[a b="c"]>baz'), result('bar[a b="c"]>baz', 5)); + deepStrictEqual(extract('<foo>bar[a b="c"]>baz', { prefix: '<' }), result('foo>bar[a b="c"]>baz', 1, 0)); + deepStrictEqual(extract('<foo>bar[a b="<"]>baz', { prefix: '<' }), result('foo>bar[a b="<"]>baz', 1, 0)); + deepStrictEqual(extract('<foo>bar{<}>baz', { prefix: '<' }), result('foo>bar{<}>baz', 1, 0)); + + // Multiple prefix characters + deepStrictEqual(extract('foo>>>bar[a b="c"]>baz', { prefix: '>>>' }), result('bar[a b="c"]>baz', 6, 3)); + + // Absent prefix + strictEqual(extract('<foo>bar[a b="c"]>baz', { prefix: '&&' }), void 0); + }); + + it('HTML test', () => { + const html = (str: string) => isAtHTMLTag(scanner(str)); + + // simple tag + ok(html('<div>')); + ok(html('<div/>')); + ok(html('<div />')); + ok(html('</div>')); + + // tag with attributes + ok(html('<div foo="bar">')); + ok(html('<div foo=bar>')); + ok(html('<div foo>')); + ok(html('<div a="b" c=d>')); + ok(html('<div a=b c=d>')); + ok(html('<div a=^b$ c=d>')); + ok(html('<div a=b c=^%d]$>')); + ok(html('<div title=привет>')); + ok(html('<div title=привет123>')); + ok(html('<foo-bar>')); + + // invalid tags + ok(!html('div>')); + ok(!html('<div')); + ok(!html('<div привет>')); + ok(!html('<div =bar>')); + ok(!html('<div foo=>')); + ok(!html('[a=b c=d]>')); + ok(!html('div[a=b c=d]>')); + }); + + it('consume quotes', () => { + let s = scanner(' "foo"'); + ok(consumeQuoted(s)); + strictEqual(s.pos, 1); + + s = scanner('"foo"'); + ok(consumeQuoted(s)); + strictEqual(s.pos, 0); + + s = scanner('""'); + ok(consumeQuoted(s)); + strictEqual(s.pos, 0); + + s = scanner('"a\\\"b"'); + ok(consumeQuoted(s)); + strictEqual(s.pos, 0); + + // don’t eat anything + s = scanner('foo'); + ok(!consumeQuoted(s)); + strictEqual(s.pos, 3); + }); +});
126
Unit tests and docs for abbreviation extractor
0
.ts
ts
mit
emmetio/emmet
10072129
<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_dependency 'sinatra', '>= 1.2.6' s.add_dependency 'simple-random' s.add_development_dependency 'rake' s.add_development_dependency 'bundler', '~> 1.6' s.add_development_dependency 'rspec', '~> 3.0' s.add_development_dependency 'rack-test' s.add_development_dependency 'coveralls' end 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 debugger gem <DFF> @@ -25,9 +25,10 @@ Gem::Specification.new do |s| s.add_dependency 'sinatra', '>= 1.2.6' s.add_dependency 'simple-random' - s.add_development_dependency 'rake' s.add_development_dependency 'bundler', '~> 1.6' - s.add_development_dependency 'rspec', '~> 3.0' - s.add_development_dependency 'rack-test' s.add_development_dependency 'coveralls' + s.add_development_dependency 'debugger' + s.add_development_dependency 'rack-test' + s.add_development_dependency 'rake' + s.add_development_dependency 'rspec', '~> 3.0' end
4
Add debugger gem
3
.gemspec
gemspec
mit
splitrb/split
10072130
<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_dependency 'sinatra', '>= 1.2.6' s.add_dependency 'simple-random' s.add_development_dependency 'rake' s.add_development_dependency 'bundler', '~> 1.6' s.add_development_dependency 'rspec', '~> 3.0' s.add_development_dependency 'rack-test' s.add_development_dependency 'coveralls' end 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 debugger gem <DFF> @@ -25,9 +25,10 @@ Gem::Specification.new do |s| s.add_dependency 'sinatra', '>= 1.2.6' s.add_dependency 'simple-random' - s.add_development_dependency 'rake' s.add_development_dependency 'bundler', '~> 1.6' - s.add_development_dependency 'rspec', '~> 3.0' - s.add_development_dependency 'rack-test' s.add_development_dependency 'coveralls' + s.add_development_dependency 'debugger' + s.add_development_dependency 'rack-test' + s.add_development_dependency 'rake' + s.add_development_dependency 'rspec', '~> 3.0' end
4
Add debugger gem
3
.gemspec
gemspec
mit
splitrb/split
10072131
<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_dependency 'sinatra', '>= 1.2.6' s.add_dependency 'simple-random' s.add_development_dependency 'rake' s.add_development_dependency 'bundler', '~> 1.6' s.add_development_dependency 'rspec', '~> 3.0' s.add_development_dependency 'rack-test' s.add_development_dependency 'coveralls' end 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 debugger gem <DFF> @@ -25,9 +25,10 @@ Gem::Specification.new do |s| s.add_dependency 'sinatra', '>= 1.2.6' s.add_dependency 'simple-random' - s.add_development_dependency 'rake' s.add_development_dependency 'bundler', '~> 1.6' - s.add_development_dependency 'rspec', '~> 3.0' - s.add_development_dependency 'rack-test' s.add_development_dependency 'coveralls' + s.add_development_dependency 'debugger' + s.add_development_dependency 'rack-test' + s.add_development_dependency 'rake' + s.add_development_dependency 'rspec', '~> 3.0' end
4
Add debugger gem
3
.gemspec
gemspec
mit
splitrb/split
10072132
<NME> transducers.js <BEF> // basic protocol helpers var symbolExists = typeof Symbol !== 'undefined'; var protocols = { iterator: symbolExists ? Symbol.iterator : '@@iterator' }; function throwProtocolError(name, coll) { throw new Error("don't know how to " + name + " collection: " + coll); } function fulfillsProtocol(obj, name) { if(name === 'iterator') { // Accept ill-formed iterators that don't conform to the // protocol by accepting just next() return obj[protocols.iterator] || obj.next; } return obj[protocols[name]]; } function getProtocolProperty(obj, name) { return obj[protocols[name]]; } function iterator(coll) { var iter = getProtocolProperty(coll, 'iterator'); if(iter) { return iter.call(coll); } else if(coll.next) { // Basic duck typing to accept an ill-formed iterator that doesn't // conform to the iterator protocol (all iterators should have the // @@iterator method and return themselves, but some engines don't // have that on generators like older v8) return coll; } else if(isArray(coll)) { return new ArrayIterator(coll); } else if(isObject(coll)) { return new ObjectIterator(coll); } } function ArrayIterator(arr) { this.arr = arr; this.index = 0; } ArrayIterator.prototype.next = function() { if(this.index < this.arr.length) { return { value: this.arr[this.index++], done: false }; } return { done: true } }; function ObjectIterator(obj) { this.obj = obj; this.keys = Object.keys(obj); this.index = 0; } ObjectIterator.prototype.next = function() { if(this.index < this.keys.length) { var k = this.keys[this.index++]; return { value: [k, this.obj[k]], done: false }; } return { done: true } }; // helpers var toString = Object.prototype.toString; var isArray = typeof Array.isArray === 'function' ? Array.isArray : function(obj) { return toString.call(obj) == '[object Array]'; }; function isFunction(x) { return typeof x === 'function'; } function isObject(x) { return x instanceof Object && Object.getPrototypeOf(x) === Object.getPrototypeOf({}); } function isNumber(x) { return typeof x === 'number'; } function Reduced(value) { this.val = val; } function reduce(coll, f, init) { if(isArray(coll)) { var result = init; var index = -1; var len = coll.length; while(++index < len) { result = f(result, coll[index]); if(result instanceof Reduced) { return result.val; } } return result; } else if(fulfillsProtocol(coll, 'iterator')) { var result = init; var iter = iterator(coll); var val = iter.next(); while(!val.done) { result = f(result, val.value); if(result instanceof Reduced) { return result.val; } val = iter.next(); } return result; } else if(isObject(coll)) { return reduce(Object.keys(coll), function(result, k) { return f(result, [k, coll[k]]); }, init); } throwProtocolError('reduce', coll); } function transduce(xform, reducer, init, coll) { reducer = xform(reducer); if(!coll) { coll = init; init = reducer.init(); } var res = reduce(coll, function(res, input) { return reducer.step(res, input); }, init); return reducer.result(res); } function compose() { while(++index < len) { result = xform['@@transducer/step'](result, coll[index]); if(isReduced(result)) { result = deref(result); break; } } return xform['@@transducer/result'](result); } else if(isObject(coll) || fulfillsProtocol(coll, 'iterator')) { var result = init; var iter = iterator(coll); var val = iter.next(); while(!val.done) { result = xform['@@transducer/step'](result, val.value); if(isReduced(result)) { result = deref(result); break; } val = iter.next(); } return xform['@@transducer/result'](result); } throwProtocolError('iterate', coll); } function transduce(coll, xform, reducer, init) { xform = xform(reducer); if(init === undefined) { init = xform['@@transducer/init'](); } return reduce(coll, xform, init); } function compose() { var funcs = Array.prototype.slice.call(arguments); return function(r) { var value = r; for(var i=funcs.length-1; i>=0; i--) { value = funcs[i](value); } return value; } } } function arrayMap(f, arr, ctx) { var index = -1; var length = arr.length; var result = Array(length); throw new Error('init value unavailable'); }; t['@@transducer/result'] = function(v) { return v; }; return result; } function arrayFilter(f, arr, ctx) { var len = arr.length; var result = []; f = bound(f, ctx, 2); if(!ctx) { return f; } else { switch(count) { case 1: return function(x) { return f.call(ctx, x); } case 2: return function(x, y) { return f.call(ctx, x, y); } default: return f.bind(ctx); } } } function arrayMap(arr, f, ctx) { var index = -1; var length = arr.length; var result = Array(length); f = bound(f, ctx, 2); while (++index < length) { result[index] = f(arr[index], index); } return result; if(coll) { if(isArray(coll)) { return arrayMap(f, coll, ctx); } return seq(coll, map(f)); } for(var i=0; i<len; i++) { if(f(arr[i], i)) { result.push(arr[i]); } } return result; } function Map(f, xform) { this.xform = xform; this.f = f; } Map.prototype['@@transducer/init'] = function() { return this.xform['@@transducer/init'](); }; Map.prototype['@@transducer/result'] = function(v) { return this.xform['@@transducer/result'](v); }; Map.prototype['@@transducer/step'] = function(res, input) { return this.xform['@@transducer/step'](res, this.f(input)); }; function map(coll, f, ctx) { if(isFunction(coll)) { ctx = f; f = coll; coll = null; } f = bound(f, ctx); if(coll) { if(isArray(coll)) { return arrayFilter(f, coll, ctx); } return seq(coll, filter(f)); } return function(xform) { return new Map(f, xform); } } function Filter(f, xform) { this.xform = xform; this.f = f; } Filter.prototype['@@transducer/init'] = function() { return this.xform['@@transducer/init'](); }; Filter.prototype['@@transducer/result'] = function(v) { return this.xform['@@transducer/result'](v); }; Filter.prototype['@@transducer/step'] = function(res, input) { if(this.f(input)) { return this.xform['@@transducer/step'](res, input); } return res; }; function filter(coll, f, ctx) { if(isFunction(coll)) { ctx = f; f = coll; coll = null; } f = bound(f, ctx); if(coll) { if(isArray(coll)) { return arrayFilter(coll, f, ctx); } return seq(coll, filter(f)); } return function(xform) { return new Filter(f, xform); }; } function remove(coll, f, ctx) { if(isFunction(coll)) { ctx = f; f = coll; coll = null; } f = bound(f, ctx); return filter(coll, function(x) { return !f(x); }); } function keep(coll) { return filter(coll, function(x) { return x != null }); } function Dedupe(xform) { this.xform = xform; this.last = undefined; } Dedupe.prototype['@@transducer/init'] = function() { return this.xform['@@transducer/init'](); }; Dedupe.prototype['@@transducer/result'] = function(v) { return this.xform['@@transducer/result'](v); }; Dedupe.prototype['@@transducer/step'] = function(result, input) { if(input !== this.last) { this.last = input; return this.xform['@@transducer/step'](result, input); } return result; }; function dedupe(coll) { if(coll) { return seq(coll, dedupe()); } return function(xform) { return new Dedupe(xform); } } function TakeWhile(f, xform) { this.xform = xform; this.f = f; } TakeWhile.prototype['@@transducer/init'] = function() { return this.xform['@@transducer/init'](); }; TakeWhile.prototype['@@transducer/result'] = function(v) { return this.xform['@@transducer/result'](v); }; TakeWhile.prototype['@@transducer/step'] = function(result, input) { if(this.f(input)) { return this.xform['@@transducer/step'](result, input); } return new Reduced(result); }; function takeWhile(coll, f, ctx) { if(isFunction(coll)) { ctx = f; f = coll; coll = null; } f = bound(f, ctx); if(coll) { return seq(coll, takeWhile(f)); } return function(xform) { return new TakeWhile(f, xform); } } function Take(n, xform) { this.n = n; this.i = 0; this.xform = xform; } Take.prototype['@@transducer/init'] = function() { return this.xform['@@transducer/init'](); }; Take.prototype['@@transducer/result'] = function(v) { return this.xform['@@transducer/result'](v); }; Take.prototype['@@transducer/step'] = function(result, input) { if (this.i < this.n) { result = this.xform['@@transducer/step'](result, input); if(this.i + 1 >= this.n) { // Finish reducing on the same step as the final value. TODO: // double-check that this doesn't break any semantics result = ensureReduced(result); } } this.i++; return result; }; function take(coll, n) { if(isNumber(coll)) { n = coll; coll = null } if(coll) { return seq(coll, take(n)); } return function(xform) { return new Take(n, xform); } } function Drop(n, xform) { this.n = n; this.i = 0; this.xform = xform; } Drop.prototype['@@transducer/init'] = function() { return this.xform['@@transducer/init'](); }; Drop.prototype['@@transducer/result'] = function(v) { return this.xform['@@transducer/result'](v); }; Drop.prototype['@@transducer/step'] = function(result, input) { if(this.i++ < this.n) { return result; } return this.xform['@@transducer/step'](result, input); }; function drop(coll, n) { if(isNumber(coll)) { n = coll; coll = null } if(coll) { return seq(coll, drop(n)); } return function(xform) { return new Drop(n, xform); } } function DropWhile(f, xform) { this.xform = xform; this.f = f; this.dropping = true; } DropWhile.prototype['@@transducer/init'] = function() { return this.xform['@@transducer/init'](); }; Cat.prototype.step = function(result, input) { var xform = this.xform; return reduce(input, function(res, input) { return xform.step(res, input) }, result); }; function cat(xform) { if(coll) { return seq(coll, dropWhile(f)); } return function(xform) { return new DropWhile(f, xform); } } function Partition(n, xform) { this.n = n; this.i = 0; this.xform = xform; this.part = new Array(n); } Partition.prototype['@@transducer/init'] = function() { return this.xform['@@transducer/init'](); }; Partition.prototype['@@transducer/result'] = function(v) { if (this.i > 0) { return ensureUnreduced(this.xform['@@transducer/step'](v, this.part.slice(0, this.i))); } return this.xform['@@transducer/result'](v); }; Partition.prototype['@@transducer/step'] = function(result, input) { this.part[this.i] = input; this.i += 1; if (this.i === this.n) { var out = this.part.slice(0, this.n); this.part = new Array(this.n); this.i = 0; return this.xform['@@transducer/step'](result, out); } return result; }; function partition(coll, n) { if (isNumber(coll)) { n = coll; coll = null; } if (coll) { return seq(coll, partition(n)); } return function(xform) { return new Partition(n, xform); }; } var NOTHING = {}; function PartitionBy(f, xform) { // TODO: take an "opts" object that allows the user to specify // equality this.f = f; this.xform = xform; this.part = []; this.last = NOTHING; function array(coll, xform) { if(!xform) { return reduce(coll, push, []); } return transduce(xform, arrayReducer, [], coll); } function obj(coll, xform) { if(!xform) { return reduce(coll, merge, {}); } return transduce(xform, objReducer, {}, coll); } PartitionBy.prototype['@@transducer/step'] = function(result, input) { var current = this.f(input); if (current === this.last || this.last === NOTHING) { this.part.push(input); } else { result = this.xform['@@transducer/step'](result, this.part); this.part = [input]; } this.last = current; return result; }; function partitionBy(coll, f, ctx) { if (isFunction(coll)) { ctx = f; f = coll; coll = null; } f = bound(f, ctx); if (coll) { return seq(coll, partitionBy(f)); } return function(xform) { return new PartitionBy(f, xform); }; } function Interpose(sep, xform) { this.sep = sep; this.xform = xform; this.started = false; } Interpose.prototype['@@transducer/init'] = function() { return this.xform['@@transducer/init'](); }; Interpose.prototype['@@transducer/result'] = function(v) { return this.xform['@@transducer/result'](v); }; Interpose.prototype['@@transducer/step'] = function(result, input) { if (this.started) { var withSep = this.xform['@@transducer/step'](result, this.sep); if (isReduced(withSep)) { return withSep; } else { return this.xform['@@transducer/step'](withSep, input); } } else { this.started = true; return this.xform['@@transducer/step'](result, input); } }; /** * Returns a new collection containing elements of the given * collection, separated by the specified separator. Returns a * transducer if a collection is not provided. */ function interpose(coll, separator) { if (arguments.length === 1) { separator = coll; return function(xform) { return new Interpose(separator, xform); }; } return seq(coll, interpose(separator)); } function Repeat(n, xform) { this.xform = xform; this.n = n; } Repeat.prototype['@@transducer/init'] = function() { return this.xform['@@transducer/init'](); }; Repeat.prototype['@@transducer/result'] = function(v) { return this.xform['@@transducer/result'](v); }; Repeat.prototype['@@transducer/step'] = function(result, input) { var n = this.n; var r = result; for (var i = 0; i < n; i++) { r = this.xform['@@transducer/step'](r, input); if (isReduced(r)) { break; } } return r; }; /** * Returns a new collection containing elements of the given * collection, each repeated n times. Returns a transducer if a * collection is not provided. */ function repeat(coll, n) { if (arguments.length === 1) { n = coll; return function(xform) { return new Repeat(n, xform); }; } return seq(coll, repeat(n)); } function TakeNth(n, xform) { this.xform = xform; this.n = n; this.i = -1; } TakeNth.prototype['@@transducer/init'] = function() { return this.xform['@@transducer/init'](); }; TakeNth.prototype['@@transducer/result'] = function(v) { return this.xform['@@transducer/result'](v); }; TakeNth.prototype['@@transducer/step'] = function(result, input) { this.i += 1; if (this.i % this.n === 0) { return this.xform['@@transducer/step'](result, input); } return result; }; /** * Returns a new collection of every nth element of the given * collection. Returns a transducer if a collection is not provided. */ function takeNth(coll, nth) { if (arguments.length === 1) { nth = coll; return function(xform) { return new TakeNth(nth, xform); }; } return seq(coll, takeNth(nth)); } // pure transducers (cannot take collections) function Cat(xform) { this.xform = xform; } Cat.prototype['@@transducer/init'] = function() { return this.xform['@@transducer/init'](); }; Cat.prototype['@@transducer/result'] = function(v) { return this.xform['@@transducer/result'](v); }; Cat.prototype['@@transducer/step'] = function(result, input) { var xform = this.xform; var newxform = {}; newxform['@@transducer/init'] = function() { return xform['@@transducer/init'](); }; newxform['@@transducer/result'] = function(v) { return v; }; newxform['@@transducer/step'] = function(result, input) { var val = xform['@@transducer/step'](result, input); return isReduced(val) ? deref(val) : val; }; return reduce(input, newxform, result); }; function cat(xform) { return new Cat(xform); } function mapcat(f, ctx) { f = bound(f, ctx); return compose(map(f), cat); } // collection helpers function push(arr, x) { arr.push(x); return arr; } function merge(obj, x) { if(isArray(x) && x.length === 2) { obj[x[0]] = x[1]; } else { var keys = Object.keys(x); var len = keys.length; for(var i=0; i<len; i++) { obj[keys[i]] = x[keys[i]]; } } return obj; } var arrayReducer = {}; arrayReducer['@@transducer/init'] = function() { return []; }; arrayReducer['@@transducer/result'] = function(v) { return v; }; arrayReducer['@@transducer/step'] = push; var objReducer = {}; objReducer['@@transducer/init'] = function() { return {}; }; objReducer['@@transducer/result'] = function(v) { return v; }; objReducer['@@transducer/step'] = merge; // building new collections function toArray(coll, xform) { if(!xform) { return reduce(coll, arrayReducer, []); } return transduce(coll, xform, arrayReducer, []); } function toObj(coll, xform) { if(!xform) { return reduce(coll, objReducer, {}); } return transduce(coll, xform, objReducer, {}); } function toIter(coll, xform) { if(!xform) { return iterator(coll); } return new LazyTransformer(xform, coll); } function seq(coll, xform) { if(isArray(coll)) { return transduce(coll, xform, arrayReducer, []); } else if(isObject(coll)) { return transduce(coll, xform, objReducer, {}); } else if(coll['@@transducer/step']) { var init; if(coll['@@transducer/init']) { init = coll['@@transducer/init'](); } else { init = new coll.constructor(); } return transduce(coll, xform, coll, init); } else if(fulfillsProtocol(coll, 'iterator')) { return new LazyTransformer(xform, coll); } throwProtocolError('sequence', coll); } function into(to, xform, from) { if(isArray(to)) { return transduce(from, xform, arrayReducer, to); } else if(isObject(to)) { return transduce(from, xform, objReducer, to); } else if(to['@@transducer/step']) { return transduce(from, xform, to, to); } throwProtocolError('into', to); } // laziness var stepper = {}; stepper['@@transducer/result'] = function(v) { return isReduced(v) ? deref(v) : v; }; stepper['@@transducer/step'] = function(lt, x) { lt.items.push(x); return lt.rest; }; function Stepper(xform, iter) { this.xform = xform(stepper); this.iter = iter; } Stepper.prototype['@@transducer/step'] = function(lt) { var len = lt.items.length; while(lt.items.length === len) { var n = this.iter.next(); if(n.done || isReduced(n.value)) { // finalize this.xform['@@transducer/result'](this); break; } // step this.xform['@@transducer/step'](lt, n.value); } } function LazyTransformer(xform, coll) { this.iter = iterator(coll); this.items = []; this.stepper = new Stepper(xform, iterator(coll)); } LazyTransformer.prototype[protocols.iterator] = function() { return this; } LazyTransformer.prototype.next = function() { this['@@transducer/step'](); if(this.items.length) { return { value: this.items.pop(), done: false } } else { return { done: true }; } }; LazyTransformer.prototype['@@transducer/step'] = function() { if(!this.items.length) { this.stepper['@@transducer/step'](this); } } // util function range(n) { var arr = new Array(n); for(var i=0; i<arr.length; i++) { arr[i] = i; } return arr; } module.exports = { reduce: reduce, transformer: transformer, Reduced: Reduced, isReduced: isReduced, iterator: iterator, push: push, merge: merge, transduce: transduce, seq: seq, toArray: toArray, toObj: toObj, toIter: toIter, into: into, compose: compose, map: map, filter: filter, remove: remove, cat: cat, mapcat: mapcat, keep: keep, dedupe: dedupe, take: take, takeWhile: takeWhile, takeNth: takeNth, drop: drop, dropWhile: dropWhile, partition: partition, partitionBy: partitionBy, interpose: interpose, repeat: repeat, range: range, LazyTransformer: LazyTransformer }; <MSG> switch coll and f order in APIs, benchmark tweaks <DFF> @@ -106,50 +106,42 @@ function Reduced(val) { this.val = val; } -function reduce(coll, f, init) { +function reduce(coll, xform, init) { if(isArray(coll)) { var result = init; var index = -1; var len = coll.length; while(++index < len) { - result = f(result, coll[index]); + result = xform.step(result, coll[index]); if(result instanceof Reduced) { return result.val; } } - return result; + return xform.result(result); } - else if(fulfillsProtocol(coll, 'iterator')) { + else if(isObject(coll) || fulfillsProtocol(coll, 'iterator')) { var result = init; var iter = iterator(coll); var val = iter.next(); while(!val.done) { - result = f(result, val.value); + result = xform.step(result, val.value); if(result instanceof Reduced) { return result.val; } val = iter.next(); } - return result; + return xform.result(result); } - else if(isObject(coll)) { - return reduce(Object.keys(coll), function(result, k) { - return f(result, [k, coll[k]]); - }, init); - } - throwProtocolError('reduce', coll); + throwProtocolError('iterate', coll); } function transduce(xform, reducer, init, coll) { - reducer = xform(reducer); + xform = xform(reducer); if(!coll) { coll = init; - init = reducer.init(); + init = xform.init(); } - var res = reduce(coll, function(res, input) { - return reducer.step(res, input); - }, init); - return reducer.result(res); + return reduce(coll, xform, init); } function compose() { @@ -199,7 +191,7 @@ function bound(f, ctx, count) { } } -function arrayMap(f, arr, ctx) { +function arrayMap(arr, f, ctx) { var index = -1; var length = arr.length; var result = Array(length); @@ -211,7 +203,7 @@ function arrayMap(f, arr, ctx) { return result; } -function arrayFilter(f, arr, ctx) { +function arrayFilter(arr, f, ctx) { var len = arr.length; var result = []; f = bound(f, ctx, 2); @@ -247,7 +239,7 @@ function map(coll, f, ctx) { if(coll) { if(isArray(coll)) { - return arrayMap(f, coll, ctx); + return arrayMap(coll, f, ctx); } return seq(coll, map(f)); } @@ -283,7 +275,7 @@ function filter(coll, f, ctx) { if(coll) { if(isArray(coll)) { - return arrayFilter(f, coll, ctx); + return arrayFilter(coll, f, ctx); } return seq(coll, filter(f)); } @@ -486,10 +478,20 @@ Cat.prototype.result = function(v) { Cat.prototype.step = function(result, input) { var xform = this.xform; + var newxform = { + init: function() { + return xform.init(); + }, + result: function(v) { + return v; + }, + step: function(result, input) { + var val = xform.step(result, input); + return (val instanceof Reduced) ? new Reduced(val) : val; + } + } - return reduce(input, function(res, input) { - return xform.step(res, input) - }, result); + return reduce(input, newxform, result); }; function cat(xform) { @@ -559,14 +561,14 @@ function getReducer(coll) { function array(coll, xform) { if(!xform) { - return reduce(coll, push, []); + return reduce(coll, arrayReducer, []); } return transduce(xform, arrayReducer, [], coll); } function obj(coll, xform) { if(!xform) { - return reduce(coll, merge, {}); + return reduce(coll, objReducer, {}); } return transduce(xform, objReducer, {}, coll); }
29
switch coll and f order in APIs, benchmark tweaks
27
.js
js
bsd-2-clause
jlongster/transducers.js
10072133
<NME> index.ngdoc <BEF> ADDFILE <MSG> chore(dgeni): Added content and assets for index page <DFF> @@ -0,0 +1,5 @@ +@ngdoc overview +@name Semantic-UI-Angular API Reference +@description + +Welcome to the Semantic-UI-Angular API docs page! \ No newline at end of file
5
chore(dgeni): Added content and assets for index page
0
.ngdoc
ngdoc
mit
Semantic-Org/Semantic-UI-Angular
10072134
<NME> index.ngdoc <BEF> ADDFILE <MSG> chore(dgeni): Added content and assets for index page <DFF> @@ -0,0 +1,5 @@ +@ngdoc overview +@name Semantic-UI-Angular API Reference +@description + +Welcome to the Semantic-UI-Angular API docs page! \ No newline at end of file
5
chore(dgeni): Added content and assets for index page
0
.ngdoc
ngdoc
mit
Semantic-Org/Semantic-UI-Angular
10072135
<NME> index.ngdoc <BEF> ADDFILE <MSG> chore(dgeni): Added content and assets for index page <DFF> @@ -0,0 +1,5 @@ +@ngdoc overview +@name Semantic-UI-Angular API Reference +@description + +Welcome to the Semantic-UI-Angular API docs page! \ No newline at end of file
5
chore(dgeni): Added content and assets for index page
0
.ngdoc
ngdoc
mit
Semantic-Org/Semantic-UI-Angular
10072136
<NME> dual_adapter_spec.rb <BEF> # frozen_string_literal: true require "spec_helper" describe Split::Persistence::DualAdapter do let(:context) { "some context" } let(:logged_in_adapter_instance) { double } let(:logged_in_adapter) do Class.new.tap { |c| allow(c).to receive(:new) { logged_in_adapter_instance } } end let(:logged_out_adapter_instance) { double } let(:logged_out_adapter) do Class.new.tap { |c| allow(c).to receive(:new) { logged_out_adapter_instance } } end context 'when logged in' do subject do described_class.with_config( logged_in: lambda { |context| true }, logged_in_adapter: logged_in_adapter, logged_out_adapter: logged_out_adapter ).new(context) end it '#[]=' do expect(logged_in_adapter_instance).to receive(:[]=).with('my_key', 'my_value') expect(logged_out_adapter_instance).to receive(:[]=).with('my_key', 'my_value') expect(logged_out_adapter_instance).to receive(:[]).with('my_key') { nil } subject['my_key'] = 'my_value' end it '#[]' do expect(logged_in_adapter_instance).to receive(:[]).with('my_key') { 'my_value' } expect_any_instance_of(logged_out_adapter).not_to receive(:[]) expect(subject['my_key']).to eq('my_value') end it '#delete' do expect(logged_in_adapter_instance).to receive(:delete).with('my_key') { 'my_value' } expect(logged_out_adapter_instance).to receive(:delete).with('my_key') { 'my_value' } expect(subject.delete('my_key')).to eq('my_value') end it '#keys' do expect(logged_in_adapter_instance).to receive(:keys) { ['my_value'] } expect(logged_out_adapter_instance).to receive(:keys) { ['my_value', 'my_value2'] } expect(subject.keys).to eq(['my_value', 'my_value2']) end end context 'when logged out' do subject do described_class.with_config( logged_in: lambda { |context| false }, logged_in_adapter: logged_in_adapter, logged_out_adapter: logged_out_adapter ).new(context) end it '#[]=' do expect_any_instance_of(logged_in_adapter).not_to receive(:[]=) expect(logged_out_adapter_instance).to receive(:[]=).with('my_key', 'my_value') expect(logged_out_adapter_instance).to receive(:[]).with('my_key') { nil } subject['my_key'] = 'my_value' end it '#[]' do expect_any_instance_of(logged_in_adapter).not_to receive(:[]) expect(logged_out_adapter_instance).to receive(:[]).with('my_key') { 'my_value' } expect(subject['my_key']).to eq('my_value') end it '#delete' do expect(logged_in_adapter_instance).to receive(:delete).with('my_key') { 'my_value' } expect(logged_out_adapter_instance).to receive(:delete).with('my_key') { 'my_value' } expect(subject.delete('my_key')).to eq('my_value') end it '#keys' do expect(logged_in_adapter_instance).to receive(:keys) { ['my_value'] } expect(logged_out_adapter_instance).to receive(:keys) { ['my_value', 'my_value2'] } expect(subject.keys).to eq(['my_value', 'my_value2']) end end describe "when errors in config" do before { described_class.config.clear } let(:some_proc) { -> { } } it "when no logged in adapter" do expect { described_class.with_config( logged_in: some_proc, logged_out_adapter: logged_out_adapter ).new(context) }.to raise_error(StandardError, /:logged_in_adapter/) end it "when no logged out adapter" do expect { described_class.with_config( logged_in: some_proc, logged_in_adapter: logged_in_adapter ).new(context) }.to raise_error(StandardError, /:logged_out_adapter/) end it "when no logged in detector" do expect { described_class.with_config( logged_in_adapter: logged_in_adapter, logged_out_adapter: logged_out_adapter ).new(context) }.to raise_error(StandardError, /:logged_in$/) end end end <MSG> Add a flag to use the new behavior of the DualAdapter <DFF> @@ -14,73 +14,149 @@ describe Split::Persistence::DualAdapter do Class.new.tap { |c| allow(c).to receive(:new) { logged_out_adapter_instance } } end - context 'when logged in' do - subject do - described_class.with_config( - logged_in: lambda { |context| true }, - logged_in_adapter: logged_in_adapter, - logged_out_adapter: logged_out_adapter - ).new(context) - end - - it '#[]=' do - expect(logged_in_adapter_instance).to receive(:[]=).with('my_key', 'my_value') - expect(logged_out_adapter_instance).to receive(:[]=).with('my_key', 'my_value') - expect(logged_out_adapter_instance).to receive(:[]).with('my_key') { nil } - subject['my_key'] = 'my_value' - end - - it '#[]' do - expect(logged_in_adapter_instance).to receive(:[]).with('my_key') { 'my_value' } - expect_any_instance_of(logged_out_adapter).not_to receive(:[]) - expect(subject['my_key']).to eq('my_value') - end - - it '#delete' do - expect(logged_in_adapter_instance).to receive(:delete).with('my_key') { 'my_value' } - expect(logged_out_adapter_instance).to receive(:delete).with('my_key') { 'my_value' } - expect(subject.delete('my_key')).to eq('my_value') + context 'when fallback_to_logged_out_adapter is false' do + context 'when logged in' do + subject do + described_class.with_config( + logged_in: lambda { |context| true }, + logged_in_adapter: logged_in_adapter, + logged_out_adapter: logged_out_adapter, + fallback_to_logged_out_adapter: false + ).new(context) + end + + it '#[]=' do + expect(logged_in_adapter_instance).to receive(:[]=).with('my_key', 'my_value') + expect_any_instance_of(logged_out_adapter).not_to receive(:[]=) + subject['my_key'] = 'my_value' + end + + it '#[]' do + expect(logged_in_adapter_instance).to receive(:[]).with('my_key') { 'my_value' } + expect_any_instance_of(logged_out_adapter).not_to receive(:[]) + expect(subject['my_key']).to eq('my_value') + end + + it '#delete' do + expect(logged_in_adapter_instance).to receive(:delete).with('my_key') { 'my_value' } + expect_any_instance_of(logged_out_adapter).not_to receive(:delete) + expect(subject.delete('my_key')).to eq('my_value') + end + + it '#keys' do + expect(logged_in_adapter_instance).to receive(:keys) { ['my_value'] } + expect_any_instance_of(logged_out_adapter).not_to receive(:keys) + expect(subject.keys).to eq(['my_value']) + end end - it '#keys' do - expect(logged_in_adapter_instance).to receive(:keys) { ['my_value'] } - expect(logged_out_adapter_instance).to receive(:keys) { ['my_value', 'my_value2'] } - expect(subject.keys).to eq(['my_value', 'my_value2']) + context 'when logged out' do + subject do + described_class.with_config( + logged_in: lambda { |context| false }, + logged_in_adapter: logged_in_adapter, + logged_out_adapter: logged_out_adapter, + fallback_to_logged_out_adapter: false + ).new(context) + end + + it '#[]=' do + expect_any_instance_of(logged_in_adapter).not_to receive(:[]=) + expect(logged_out_adapter_instance).to receive(:[]=).with('my_key', 'my_value') + subject['my_key'] = 'my_value' + end + + it '#[]' do + expect_any_instance_of(logged_in_adapter).not_to receive(:[]) + expect(logged_out_adapter_instance).to receive(:[]).with('my_key') { 'my_value' } + expect(subject['my_key']).to eq('my_value') + end + + it '#delete' do + expect_any_instance_of(logged_in_adapter).not_to receive(:delete) + expect(logged_out_adapter_instance).to receive(:delete).with('my_key') { 'my_value' } + expect(subject.delete('my_key')).to eq('my_value') + end + + it '#keys' do + expect_any_instance_of(logged_in_adapter).not_to receive(:keys) + expect(logged_out_adapter_instance).to receive(:keys) { ['my_value', 'my_value2'] } + expect(subject.keys).to eq(['my_value', 'my_value2']) + end end end - context 'when logged out' do - subject do - described_class.with_config( - logged_in: lambda { |context| false }, - logged_in_adapter: logged_in_adapter, - logged_out_adapter: logged_out_adapter - ).new(context) - end - - it '#[]=' do - expect_any_instance_of(logged_in_adapter).not_to receive(:[]=) - expect(logged_out_adapter_instance).to receive(:[]=).with('my_key', 'my_value') - expect(logged_out_adapter_instance).to receive(:[]).with('my_key') { nil } - subject['my_key'] = 'my_value' - end - - it '#[]' do - expect_any_instance_of(logged_in_adapter).not_to receive(:[]) - expect(logged_out_adapter_instance).to receive(:[]).with('my_key') { 'my_value' } - expect(subject['my_key']).to eq('my_value') - end - - it '#delete' do - expect(logged_in_adapter_instance).to receive(:delete).with('my_key') { 'my_value' } - expect(logged_out_adapter_instance).to receive(:delete).with('my_key') { 'my_value' } - expect(subject.delete('my_key')).to eq('my_value') + context 'when fallback_to_logged_out_adapter is true' do + context 'when logged in' do + subject do + described_class.with_config( + logged_in: lambda { |context| true }, + logged_in_adapter: logged_in_adapter, + logged_out_adapter: logged_out_adapter, + fallback_to_logged_out_adapter: true + ).new(context) + end + + it '#[]=' do + expect(logged_in_adapter_instance).to receive(:[]=).with('my_key', 'my_value') + expect(logged_out_adapter_instance).to receive(:[]=).with('my_key', 'my_value') + expect(logged_out_adapter_instance).to receive(:[]).with('my_key') { nil } + subject['my_key'] = 'my_value' + end + + it '#[]' do + expect(logged_in_adapter_instance).to receive(:[]).with('my_key') { 'my_value' } + expect_any_instance_of(logged_out_adapter).not_to receive(:[]) + expect(subject['my_key']).to eq('my_value') + end + + it '#delete' do + expect(logged_in_adapter_instance).to receive(:delete).with('my_key') { 'my_value' } + expect(logged_out_adapter_instance).to receive(:delete).with('my_key') { 'my_value' } + expect(subject.delete('my_key')).to eq('my_value') + end + + it '#keys' do + expect(logged_in_adapter_instance).to receive(:keys) { ['my_value'] } + expect(logged_out_adapter_instance).to receive(:keys) { ['my_value', 'my_value2'] } + expect(subject.keys).to eq(['my_value', 'my_value2']) + end end - it '#keys' do - expect(logged_in_adapter_instance).to receive(:keys) { ['my_value'] } - expect(logged_out_adapter_instance).to receive(:keys) { ['my_value', 'my_value2'] } - expect(subject.keys).to eq(['my_value', 'my_value2']) + context 'when logged out' do + subject do + described_class.with_config( + logged_in: lambda { |context| false }, + logged_in_adapter: logged_in_adapter, + logged_out_adapter: logged_out_adapter, + fallback_to_logged_out_adapter: true + ).new(context) + end + + it '#[]=' do + expect_any_instance_of(logged_in_adapter).not_to receive(:[]=) + expect(logged_out_adapter_instance).to receive(:[]=).with('my_key', 'my_value') + expect(logged_out_adapter_instance).to receive(:[]).with('my_key') { nil } + subject['my_key'] = 'my_value' + end + + it '#[]' do + expect_any_instance_of(logged_in_adapter).not_to receive(:[]) + expect(logged_out_adapter_instance).to receive(:[]).with('my_key') { 'my_value' } + expect(subject['my_key']).to eq('my_value') + end + + it '#delete' do + expect(logged_in_adapter_instance).to receive(:delete).with('my_key') { 'my_value' } + expect(logged_out_adapter_instance).to receive(:delete).with('my_key') { 'my_value' } + expect(subject.delete('my_key')).to eq('my_value') + end + + it '#keys' do + expect(logged_in_adapter_instance).to receive(:keys) { ['my_value'] } + expect(logged_out_adapter_instance).to receive(:keys) { ['my_value', 'my_value2'] } + expect(subject.keys).to eq(['my_value', 'my_value2']) + end end end
136
Add a flag to use the new behavior of the DualAdapter
60
.rb
rb
mit
splitrb/split
10072137
<NME> dual_adapter_spec.rb <BEF> # frozen_string_literal: true require "spec_helper" describe Split::Persistence::DualAdapter do let(:context) { "some context" } let(:logged_in_adapter_instance) { double } let(:logged_in_adapter) do Class.new.tap { |c| allow(c).to receive(:new) { logged_in_adapter_instance } } end let(:logged_out_adapter_instance) { double } let(:logged_out_adapter) do Class.new.tap { |c| allow(c).to receive(:new) { logged_out_adapter_instance } } end context 'when logged in' do subject do described_class.with_config( logged_in: lambda { |context| true }, logged_in_adapter: logged_in_adapter, logged_out_adapter: logged_out_adapter ).new(context) end it '#[]=' do expect(logged_in_adapter_instance).to receive(:[]=).with('my_key', 'my_value') expect(logged_out_adapter_instance).to receive(:[]=).with('my_key', 'my_value') expect(logged_out_adapter_instance).to receive(:[]).with('my_key') { nil } subject['my_key'] = 'my_value' end it '#[]' do expect(logged_in_adapter_instance).to receive(:[]).with('my_key') { 'my_value' } expect_any_instance_of(logged_out_adapter).not_to receive(:[]) expect(subject['my_key']).to eq('my_value') end it '#delete' do expect(logged_in_adapter_instance).to receive(:delete).with('my_key') { 'my_value' } expect(logged_out_adapter_instance).to receive(:delete).with('my_key') { 'my_value' } expect(subject.delete('my_key')).to eq('my_value') end it '#keys' do expect(logged_in_adapter_instance).to receive(:keys) { ['my_value'] } expect(logged_out_adapter_instance).to receive(:keys) { ['my_value', 'my_value2'] } expect(subject.keys).to eq(['my_value', 'my_value2']) end end context 'when logged out' do subject do described_class.with_config( logged_in: lambda { |context| false }, logged_in_adapter: logged_in_adapter, logged_out_adapter: logged_out_adapter ).new(context) end it '#[]=' do expect_any_instance_of(logged_in_adapter).not_to receive(:[]=) expect(logged_out_adapter_instance).to receive(:[]=).with('my_key', 'my_value') expect(logged_out_adapter_instance).to receive(:[]).with('my_key') { nil } subject['my_key'] = 'my_value' end it '#[]' do expect_any_instance_of(logged_in_adapter).not_to receive(:[]) expect(logged_out_adapter_instance).to receive(:[]).with('my_key') { 'my_value' } expect(subject['my_key']).to eq('my_value') end it '#delete' do expect(logged_in_adapter_instance).to receive(:delete).with('my_key') { 'my_value' } expect(logged_out_adapter_instance).to receive(:delete).with('my_key') { 'my_value' } expect(subject.delete('my_key')).to eq('my_value') end it '#keys' do expect(logged_in_adapter_instance).to receive(:keys) { ['my_value'] } expect(logged_out_adapter_instance).to receive(:keys) { ['my_value', 'my_value2'] } expect(subject.keys).to eq(['my_value', 'my_value2']) end end describe "when errors in config" do before { described_class.config.clear } let(:some_proc) { -> { } } it "when no logged in adapter" do expect { described_class.with_config( logged_in: some_proc, logged_out_adapter: logged_out_adapter ).new(context) }.to raise_error(StandardError, /:logged_in_adapter/) end it "when no logged out adapter" do expect { described_class.with_config( logged_in: some_proc, logged_in_adapter: logged_in_adapter ).new(context) }.to raise_error(StandardError, /:logged_out_adapter/) end it "when no logged in detector" do expect { described_class.with_config( logged_in_adapter: logged_in_adapter, logged_out_adapter: logged_out_adapter ).new(context) }.to raise_error(StandardError, /:logged_in$/) end end end <MSG> Add a flag to use the new behavior of the DualAdapter <DFF> @@ -14,73 +14,149 @@ describe Split::Persistence::DualAdapter do Class.new.tap { |c| allow(c).to receive(:new) { logged_out_adapter_instance } } end - context 'when logged in' do - subject do - described_class.with_config( - logged_in: lambda { |context| true }, - logged_in_adapter: logged_in_adapter, - logged_out_adapter: logged_out_adapter - ).new(context) - end - - it '#[]=' do - expect(logged_in_adapter_instance).to receive(:[]=).with('my_key', 'my_value') - expect(logged_out_adapter_instance).to receive(:[]=).with('my_key', 'my_value') - expect(logged_out_adapter_instance).to receive(:[]).with('my_key') { nil } - subject['my_key'] = 'my_value' - end - - it '#[]' do - expect(logged_in_adapter_instance).to receive(:[]).with('my_key') { 'my_value' } - expect_any_instance_of(logged_out_adapter).not_to receive(:[]) - expect(subject['my_key']).to eq('my_value') - end - - it '#delete' do - expect(logged_in_adapter_instance).to receive(:delete).with('my_key') { 'my_value' } - expect(logged_out_adapter_instance).to receive(:delete).with('my_key') { 'my_value' } - expect(subject.delete('my_key')).to eq('my_value') + context 'when fallback_to_logged_out_adapter is false' do + context 'when logged in' do + subject do + described_class.with_config( + logged_in: lambda { |context| true }, + logged_in_adapter: logged_in_adapter, + logged_out_adapter: logged_out_adapter, + fallback_to_logged_out_adapter: false + ).new(context) + end + + it '#[]=' do + expect(logged_in_adapter_instance).to receive(:[]=).with('my_key', 'my_value') + expect_any_instance_of(logged_out_adapter).not_to receive(:[]=) + subject['my_key'] = 'my_value' + end + + it '#[]' do + expect(logged_in_adapter_instance).to receive(:[]).with('my_key') { 'my_value' } + expect_any_instance_of(logged_out_adapter).not_to receive(:[]) + expect(subject['my_key']).to eq('my_value') + end + + it '#delete' do + expect(logged_in_adapter_instance).to receive(:delete).with('my_key') { 'my_value' } + expect_any_instance_of(logged_out_adapter).not_to receive(:delete) + expect(subject.delete('my_key')).to eq('my_value') + end + + it '#keys' do + expect(logged_in_adapter_instance).to receive(:keys) { ['my_value'] } + expect_any_instance_of(logged_out_adapter).not_to receive(:keys) + expect(subject.keys).to eq(['my_value']) + end end - it '#keys' do - expect(logged_in_adapter_instance).to receive(:keys) { ['my_value'] } - expect(logged_out_adapter_instance).to receive(:keys) { ['my_value', 'my_value2'] } - expect(subject.keys).to eq(['my_value', 'my_value2']) + context 'when logged out' do + subject do + described_class.with_config( + logged_in: lambda { |context| false }, + logged_in_adapter: logged_in_adapter, + logged_out_adapter: logged_out_adapter, + fallback_to_logged_out_adapter: false + ).new(context) + end + + it '#[]=' do + expect_any_instance_of(logged_in_adapter).not_to receive(:[]=) + expect(logged_out_adapter_instance).to receive(:[]=).with('my_key', 'my_value') + subject['my_key'] = 'my_value' + end + + it '#[]' do + expect_any_instance_of(logged_in_adapter).not_to receive(:[]) + expect(logged_out_adapter_instance).to receive(:[]).with('my_key') { 'my_value' } + expect(subject['my_key']).to eq('my_value') + end + + it '#delete' do + expect_any_instance_of(logged_in_adapter).not_to receive(:delete) + expect(logged_out_adapter_instance).to receive(:delete).with('my_key') { 'my_value' } + expect(subject.delete('my_key')).to eq('my_value') + end + + it '#keys' do + expect_any_instance_of(logged_in_adapter).not_to receive(:keys) + expect(logged_out_adapter_instance).to receive(:keys) { ['my_value', 'my_value2'] } + expect(subject.keys).to eq(['my_value', 'my_value2']) + end end end - context 'when logged out' do - subject do - described_class.with_config( - logged_in: lambda { |context| false }, - logged_in_adapter: logged_in_adapter, - logged_out_adapter: logged_out_adapter - ).new(context) - end - - it '#[]=' do - expect_any_instance_of(logged_in_adapter).not_to receive(:[]=) - expect(logged_out_adapter_instance).to receive(:[]=).with('my_key', 'my_value') - expect(logged_out_adapter_instance).to receive(:[]).with('my_key') { nil } - subject['my_key'] = 'my_value' - end - - it '#[]' do - expect_any_instance_of(logged_in_adapter).not_to receive(:[]) - expect(logged_out_adapter_instance).to receive(:[]).with('my_key') { 'my_value' } - expect(subject['my_key']).to eq('my_value') - end - - it '#delete' do - expect(logged_in_adapter_instance).to receive(:delete).with('my_key') { 'my_value' } - expect(logged_out_adapter_instance).to receive(:delete).with('my_key') { 'my_value' } - expect(subject.delete('my_key')).to eq('my_value') + context 'when fallback_to_logged_out_adapter is true' do + context 'when logged in' do + subject do + described_class.with_config( + logged_in: lambda { |context| true }, + logged_in_adapter: logged_in_adapter, + logged_out_adapter: logged_out_adapter, + fallback_to_logged_out_adapter: true + ).new(context) + end + + it '#[]=' do + expect(logged_in_adapter_instance).to receive(:[]=).with('my_key', 'my_value') + expect(logged_out_adapter_instance).to receive(:[]=).with('my_key', 'my_value') + expect(logged_out_adapter_instance).to receive(:[]).with('my_key') { nil } + subject['my_key'] = 'my_value' + end + + it '#[]' do + expect(logged_in_adapter_instance).to receive(:[]).with('my_key') { 'my_value' } + expect_any_instance_of(logged_out_adapter).not_to receive(:[]) + expect(subject['my_key']).to eq('my_value') + end + + it '#delete' do + expect(logged_in_adapter_instance).to receive(:delete).with('my_key') { 'my_value' } + expect(logged_out_adapter_instance).to receive(:delete).with('my_key') { 'my_value' } + expect(subject.delete('my_key')).to eq('my_value') + end + + it '#keys' do + expect(logged_in_adapter_instance).to receive(:keys) { ['my_value'] } + expect(logged_out_adapter_instance).to receive(:keys) { ['my_value', 'my_value2'] } + expect(subject.keys).to eq(['my_value', 'my_value2']) + end end - it '#keys' do - expect(logged_in_adapter_instance).to receive(:keys) { ['my_value'] } - expect(logged_out_adapter_instance).to receive(:keys) { ['my_value', 'my_value2'] } - expect(subject.keys).to eq(['my_value', 'my_value2']) + context 'when logged out' do + subject do + described_class.with_config( + logged_in: lambda { |context| false }, + logged_in_adapter: logged_in_adapter, + logged_out_adapter: logged_out_adapter, + fallback_to_logged_out_adapter: true + ).new(context) + end + + it '#[]=' do + expect_any_instance_of(logged_in_adapter).not_to receive(:[]=) + expect(logged_out_adapter_instance).to receive(:[]=).with('my_key', 'my_value') + expect(logged_out_adapter_instance).to receive(:[]).with('my_key') { nil } + subject['my_key'] = 'my_value' + end + + it '#[]' do + expect_any_instance_of(logged_in_adapter).not_to receive(:[]) + expect(logged_out_adapter_instance).to receive(:[]).with('my_key') { 'my_value' } + expect(subject['my_key']).to eq('my_value') + end + + it '#delete' do + expect(logged_in_adapter_instance).to receive(:delete).with('my_key') { 'my_value' } + expect(logged_out_adapter_instance).to receive(:delete).with('my_key') { 'my_value' } + expect(subject.delete('my_key')).to eq('my_value') + end + + it '#keys' do + expect(logged_in_adapter_instance).to receive(:keys) { ['my_value'] } + expect(logged_out_adapter_instance).to receive(:keys) { ['my_value', 'my_value2'] } + expect(subject.keys).to eq(['my_value', 'my_value2']) + end end end
136
Add a flag to use the new behavior of the DualAdapter
60
.rb
rb
mit
splitrb/split
10072138
<NME> dual_adapter_spec.rb <BEF> # frozen_string_literal: true require "spec_helper" describe Split::Persistence::DualAdapter do let(:context) { "some context" } let(:logged_in_adapter_instance) { double } let(:logged_in_adapter) do Class.new.tap { |c| allow(c).to receive(:new) { logged_in_adapter_instance } } end let(:logged_out_adapter_instance) { double } let(:logged_out_adapter) do Class.new.tap { |c| allow(c).to receive(:new) { logged_out_adapter_instance } } end context 'when logged in' do subject do described_class.with_config( logged_in: lambda { |context| true }, logged_in_adapter: logged_in_adapter, logged_out_adapter: logged_out_adapter ).new(context) end it '#[]=' do expect(logged_in_adapter_instance).to receive(:[]=).with('my_key', 'my_value') expect(logged_out_adapter_instance).to receive(:[]=).with('my_key', 'my_value') expect(logged_out_adapter_instance).to receive(:[]).with('my_key') { nil } subject['my_key'] = 'my_value' end it '#[]' do expect(logged_in_adapter_instance).to receive(:[]).with('my_key') { 'my_value' } expect_any_instance_of(logged_out_adapter).not_to receive(:[]) expect(subject['my_key']).to eq('my_value') end it '#delete' do expect(logged_in_adapter_instance).to receive(:delete).with('my_key') { 'my_value' } expect(logged_out_adapter_instance).to receive(:delete).with('my_key') { 'my_value' } expect(subject.delete('my_key')).to eq('my_value') end it '#keys' do expect(logged_in_adapter_instance).to receive(:keys) { ['my_value'] } expect(logged_out_adapter_instance).to receive(:keys) { ['my_value', 'my_value2'] } expect(subject.keys).to eq(['my_value', 'my_value2']) end end context 'when logged out' do subject do described_class.with_config( logged_in: lambda { |context| false }, logged_in_adapter: logged_in_adapter, logged_out_adapter: logged_out_adapter ).new(context) end it '#[]=' do expect_any_instance_of(logged_in_adapter).not_to receive(:[]=) expect(logged_out_adapter_instance).to receive(:[]=).with('my_key', 'my_value') expect(logged_out_adapter_instance).to receive(:[]).with('my_key') { nil } subject['my_key'] = 'my_value' end it '#[]' do expect_any_instance_of(logged_in_adapter).not_to receive(:[]) expect(logged_out_adapter_instance).to receive(:[]).with('my_key') { 'my_value' } expect(subject['my_key']).to eq('my_value') end it '#delete' do expect(logged_in_adapter_instance).to receive(:delete).with('my_key') { 'my_value' } expect(logged_out_adapter_instance).to receive(:delete).with('my_key') { 'my_value' } expect(subject.delete('my_key')).to eq('my_value') end it '#keys' do expect(logged_in_adapter_instance).to receive(:keys) { ['my_value'] } expect(logged_out_adapter_instance).to receive(:keys) { ['my_value', 'my_value2'] } expect(subject.keys).to eq(['my_value', 'my_value2']) end end describe "when errors in config" do before { described_class.config.clear } let(:some_proc) { -> { } } it "when no logged in adapter" do expect { described_class.with_config( logged_in: some_proc, logged_out_adapter: logged_out_adapter ).new(context) }.to raise_error(StandardError, /:logged_in_adapter/) end it "when no logged out adapter" do expect { described_class.with_config( logged_in: some_proc, logged_in_adapter: logged_in_adapter ).new(context) }.to raise_error(StandardError, /:logged_out_adapter/) end it "when no logged in detector" do expect { described_class.with_config( logged_in_adapter: logged_in_adapter, logged_out_adapter: logged_out_adapter ).new(context) }.to raise_error(StandardError, /:logged_in$/) end end end <MSG> Add a flag to use the new behavior of the DualAdapter <DFF> @@ -14,73 +14,149 @@ describe Split::Persistence::DualAdapter do Class.new.tap { |c| allow(c).to receive(:new) { logged_out_adapter_instance } } end - context 'when logged in' do - subject do - described_class.with_config( - logged_in: lambda { |context| true }, - logged_in_adapter: logged_in_adapter, - logged_out_adapter: logged_out_adapter - ).new(context) - end - - it '#[]=' do - expect(logged_in_adapter_instance).to receive(:[]=).with('my_key', 'my_value') - expect(logged_out_adapter_instance).to receive(:[]=).with('my_key', 'my_value') - expect(logged_out_adapter_instance).to receive(:[]).with('my_key') { nil } - subject['my_key'] = 'my_value' - end - - it '#[]' do - expect(logged_in_adapter_instance).to receive(:[]).with('my_key') { 'my_value' } - expect_any_instance_of(logged_out_adapter).not_to receive(:[]) - expect(subject['my_key']).to eq('my_value') - end - - it '#delete' do - expect(logged_in_adapter_instance).to receive(:delete).with('my_key') { 'my_value' } - expect(logged_out_adapter_instance).to receive(:delete).with('my_key') { 'my_value' } - expect(subject.delete('my_key')).to eq('my_value') + context 'when fallback_to_logged_out_adapter is false' do + context 'when logged in' do + subject do + described_class.with_config( + logged_in: lambda { |context| true }, + logged_in_adapter: logged_in_adapter, + logged_out_adapter: logged_out_adapter, + fallback_to_logged_out_adapter: false + ).new(context) + end + + it '#[]=' do + expect(logged_in_adapter_instance).to receive(:[]=).with('my_key', 'my_value') + expect_any_instance_of(logged_out_adapter).not_to receive(:[]=) + subject['my_key'] = 'my_value' + end + + it '#[]' do + expect(logged_in_adapter_instance).to receive(:[]).with('my_key') { 'my_value' } + expect_any_instance_of(logged_out_adapter).not_to receive(:[]) + expect(subject['my_key']).to eq('my_value') + end + + it '#delete' do + expect(logged_in_adapter_instance).to receive(:delete).with('my_key') { 'my_value' } + expect_any_instance_of(logged_out_adapter).not_to receive(:delete) + expect(subject.delete('my_key')).to eq('my_value') + end + + it '#keys' do + expect(logged_in_adapter_instance).to receive(:keys) { ['my_value'] } + expect_any_instance_of(logged_out_adapter).not_to receive(:keys) + expect(subject.keys).to eq(['my_value']) + end end - it '#keys' do - expect(logged_in_adapter_instance).to receive(:keys) { ['my_value'] } - expect(logged_out_adapter_instance).to receive(:keys) { ['my_value', 'my_value2'] } - expect(subject.keys).to eq(['my_value', 'my_value2']) + context 'when logged out' do + subject do + described_class.with_config( + logged_in: lambda { |context| false }, + logged_in_adapter: logged_in_adapter, + logged_out_adapter: logged_out_adapter, + fallback_to_logged_out_adapter: false + ).new(context) + end + + it '#[]=' do + expect_any_instance_of(logged_in_adapter).not_to receive(:[]=) + expect(logged_out_adapter_instance).to receive(:[]=).with('my_key', 'my_value') + subject['my_key'] = 'my_value' + end + + it '#[]' do + expect_any_instance_of(logged_in_adapter).not_to receive(:[]) + expect(logged_out_adapter_instance).to receive(:[]).with('my_key') { 'my_value' } + expect(subject['my_key']).to eq('my_value') + end + + it '#delete' do + expect_any_instance_of(logged_in_adapter).not_to receive(:delete) + expect(logged_out_adapter_instance).to receive(:delete).with('my_key') { 'my_value' } + expect(subject.delete('my_key')).to eq('my_value') + end + + it '#keys' do + expect_any_instance_of(logged_in_adapter).not_to receive(:keys) + expect(logged_out_adapter_instance).to receive(:keys) { ['my_value', 'my_value2'] } + expect(subject.keys).to eq(['my_value', 'my_value2']) + end end end - context 'when logged out' do - subject do - described_class.with_config( - logged_in: lambda { |context| false }, - logged_in_adapter: logged_in_adapter, - logged_out_adapter: logged_out_adapter - ).new(context) - end - - it '#[]=' do - expect_any_instance_of(logged_in_adapter).not_to receive(:[]=) - expect(logged_out_adapter_instance).to receive(:[]=).with('my_key', 'my_value') - expect(logged_out_adapter_instance).to receive(:[]).with('my_key') { nil } - subject['my_key'] = 'my_value' - end - - it '#[]' do - expect_any_instance_of(logged_in_adapter).not_to receive(:[]) - expect(logged_out_adapter_instance).to receive(:[]).with('my_key') { 'my_value' } - expect(subject['my_key']).to eq('my_value') - end - - it '#delete' do - expect(logged_in_adapter_instance).to receive(:delete).with('my_key') { 'my_value' } - expect(logged_out_adapter_instance).to receive(:delete).with('my_key') { 'my_value' } - expect(subject.delete('my_key')).to eq('my_value') + context 'when fallback_to_logged_out_adapter is true' do + context 'when logged in' do + subject do + described_class.with_config( + logged_in: lambda { |context| true }, + logged_in_adapter: logged_in_adapter, + logged_out_adapter: logged_out_adapter, + fallback_to_logged_out_adapter: true + ).new(context) + end + + it '#[]=' do + expect(logged_in_adapter_instance).to receive(:[]=).with('my_key', 'my_value') + expect(logged_out_adapter_instance).to receive(:[]=).with('my_key', 'my_value') + expect(logged_out_adapter_instance).to receive(:[]).with('my_key') { nil } + subject['my_key'] = 'my_value' + end + + it '#[]' do + expect(logged_in_adapter_instance).to receive(:[]).with('my_key') { 'my_value' } + expect_any_instance_of(logged_out_adapter).not_to receive(:[]) + expect(subject['my_key']).to eq('my_value') + end + + it '#delete' do + expect(logged_in_adapter_instance).to receive(:delete).with('my_key') { 'my_value' } + expect(logged_out_adapter_instance).to receive(:delete).with('my_key') { 'my_value' } + expect(subject.delete('my_key')).to eq('my_value') + end + + it '#keys' do + expect(logged_in_adapter_instance).to receive(:keys) { ['my_value'] } + expect(logged_out_adapter_instance).to receive(:keys) { ['my_value', 'my_value2'] } + expect(subject.keys).to eq(['my_value', 'my_value2']) + end end - it '#keys' do - expect(logged_in_adapter_instance).to receive(:keys) { ['my_value'] } - expect(logged_out_adapter_instance).to receive(:keys) { ['my_value', 'my_value2'] } - expect(subject.keys).to eq(['my_value', 'my_value2']) + context 'when logged out' do + subject do + described_class.with_config( + logged_in: lambda { |context| false }, + logged_in_adapter: logged_in_adapter, + logged_out_adapter: logged_out_adapter, + fallback_to_logged_out_adapter: true + ).new(context) + end + + it '#[]=' do + expect_any_instance_of(logged_in_adapter).not_to receive(:[]=) + expect(logged_out_adapter_instance).to receive(:[]=).with('my_key', 'my_value') + expect(logged_out_adapter_instance).to receive(:[]).with('my_key') { nil } + subject['my_key'] = 'my_value' + end + + it '#[]' do + expect_any_instance_of(logged_in_adapter).not_to receive(:[]) + expect(logged_out_adapter_instance).to receive(:[]).with('my_key') { 'my_value' } + expect(subject['my_key']).to eq('my_value') + end + + it '#delete' do + expect(logged_in_adapter_instance).to receive(:delete).with('my_key') { 'my_value' } + expect(logged_out_adapter_instance).to receive(:delete).with('my_key') { 'my_value' } + expect(subject.delete('my_key')).to eq('my_value') + end + + it '#keys' do + expect(logged_in_adapter_instance).to receive(:keys) { ['my_value'] } + expect(logged_out_adapter_instance).to receive(:keys) { ['my_value', 'my_value2'] } + expect(subject.keys).to eq(['my_value', 'my_value2']) + end end end
136
Add a flag to use the new behavior of the DualAdapter
60
.rb
rb
mit
splitrb/split
10072139
<NME> experiment_spec.rb <BEF> # frozen_string_literal: true require "spec_helper" require "time" describe Split::Experiment do def new_experiment(goals = []) Split::Experiment.new("link_color", alternatives: ["blue", "red", "green"], goals: goals) end def alternative(color) Split::Alternative.new(color, "link_color") end let(:experiment) { new_experiment } let(:blue) { alternative("blue") } let(:green) { alternative("green") } context "with an experiment" do let(:experiment) { Split::Experiment.new("basket_text", alternatives: ["Basket", "Cart"]) } it "should have a name" do expect(experiment.name).to eq("basket_text") end it "should have alternatives" do expect(experiment.alternatives.length).to be 2 end it "should have alternatives with correct names" do expect(experiment.alternatives.collect { |a| a.name }).to eq(["Basket", "Cart"]) end it "should be resettable by default" do expect(experiment.resettable).to be_truthy end it "should save to redis" do experiment.save expect(Split.redis.exists?("basket_text")).to be true end it "should save the start time to redis" do experiment_start_time = Time.at(1372167761) expect(Time).to receive(:now).and_return(experiment_start_time) experiment.save expect(Split::ExperimentCatalog.find("basket_text").start_time).to eq(experiment_start_time) end it "should not save the start time to redis when start_manually is enabled" do expect(Split.configuration).to receive(:start_manually).and_return(true) experiment.save expect(Split::ExperimentCatalog.find("basket_text").start_time).to be_nil end it "should save the selected algorithm to redis" do experiment_algorithm = Split::Algorithms::Whiplash experiment.algorithm = experiment_algorithm experiment.save expect(Split::ExperimentCatalog.find("basket_text").algorithm).to eq(experiment_algorithm) end it "should handle having a start time stored as a string" do experiment_start_time = Time.parse("Sat Mar 03 14:01:03") expect(Time).to receive(:now).twice.and_return(experiment_start_time) experiment.save Split.redis.hset(:experiment_start_times, experiment.name, experiment_start_time.to_s) expect(Split::ExperimentCatalog.find("basket_text").start_time).to eq(experiment_start_time) end it "should handle not having a start time" do experiment_start_time = Time.parse("Sat Mar 03 14:01:03") expect(Time).to receive(:now).and_return(experiment_start_time) experiment.save Split.redis.hdel(:experiment_start_times, experiment.name) expect(Split::ExperimentCatalog.find("basket_text").start_time).to be_nil end it "should not create duplicates when saving multiple times" do experiment.save experiment.save expect(Split.redis.exists?("basket_text")).to be true expect(Split.redis.lrange("basket_text", 0, -1)).to eq(['{"Basket":1}', '{"Cart":1}']) end describe "new record?" do it "should know if it hasn't been saved yet" do expect(experiment.new_record?).to be_truthy end it "should know if it has been saved yet" do experiment.save expect(experiment.new_record?).to be_falsey end end describe "control" do it "should be the first alternative" do experiment.save expect(experiment.control.name).to eq("Basket") end end end describe "initialization" do it "should set the algorithm when passed as an option to the initializer" do experiment = Split::Experiment.new("basket_text", alternatives: ["Basket", "Cart"], algorithm: Split::Algorithms::Whiplash) expect(experiment.algorithm).to eq(Split::Algorithms::Whiplash) end it "should be possible to make an experiment not resettable" do experiment = Split::Experiment.new("basket_text", alternatives: ["Basket", "Cart"], resettable: false) expect(experiment.resettable).to be_falsey end experiment.next_alternative.name.should eql('green') end end end end describe "persistent configuration" do it "should persist resettable in redis" do experiment = Split::Experiment.new("basket_text", alternatives: ["Basket", "Cart"], resettable: false) experiment.save e = Split::ExperimentCatalog.find("basket_text") expect(e).to eq(experiment) expect(e.resettable).to be_falsey end describe "#metadata" do let(:experiment) { Split::Experiment.new("basket_text", alternatives: ["Basket", "Cart"], algorithm: Split::Algorithms::Whiplash, metadata: meta) } let(:meta) { { a: "b" } } before do experiment.save end it "should delete the key when metadata is removed" do experiment.metadata = nil experiment.save expect(Split.redis.exists?(experiment.metadata_key)).to be_falsey end context "simple hash" do let(:meta) { { "basket" => "a", "cart" => "b" } } it "should persist metadata in redis" do e = Split::ExperimentCatalog.find("basket_text") expect(e).to eq(experiment) expect(e.metadata).to eq(meta) end end context "nested hash" do let(:meta) { { "basket" => { "one" => "two" }, "cart" => "b" } } it "should persist metadata in redis" do e = Split::ExperimentCatalog.find("basket_text") expect(e).to eq(experiment) expect(e.metadata).to eq(meta) end end end it "should persist algorithm in redis" do experiment = Split::Experiment.new("basket_text", alternatives: ["Basket", "Cart"], algorithm: Split::Algorithms::Whiplash) experiment.save e = Split::ExperimentCatalog.find("basket_text") expect(e).to eq(experiment) expect(e.algorithm).to eq(Split::Algorithms::Whiplash) end it "should persist a new experiment in redis, that does not exist in the configuration file" do experiment = Split::Experiment.new("foobar", alternatives: ["tra", "la"], algorithm: Split::Algorithms::Whiplash) experiment.save e = Split::ExperimentCatalog.find("foobar") expect(e).to eq(experiment) expect(e.alternatives.collect { |a| a.name }).to eq(["tra", "la"]) end end describe "deleting" do it "should delete itself" do experiment = Split::Experiment.new("basket_text", alternatives: [ "Basket", "Cart"]) experiment.save experiment.delete expect(Split.redis.exists?("link_color")).to be false expect(Split::ExperimentCatalog.find("link_color")).to be_nil end it "should increment the version" do expect(experiment.version).to eq(0) experiment.delete expect(experiment.version).to eq(1) end it "should call the on_experiment_delete hook" do expect(Split.configuration.on_experiment_delete).to receive(:call) experiment.delete end it "should call the on_before_experiment_delete hook" do expect(Split.configuration.on_before_experiment_delete).to receive(:call) experiment.delete end it "should reset the start time if the experiment should be manually started" do Split.configuration.start_manually = true experiment.start experiment.delete expect(experiment.start_time).to be_nil end it "should default cohorting back to false" do experiment.disable_cohorting expect(experiment.cohorting_disabled?).to eq(true) experiment.delete expect(experiment.cohorting_disabled?).to eq(false) end end describe "winner" do it "should have no winner initially" do expect(experiment.winner).to be_nil end end describe "winner=" do it "should allow you to specify a winner" do experiment.save experiment.winner = "red" expect(experiment.winner.name).to eq("red") end it "should call the on_experiment_winner_choose hook" do expect(Split.configuration.on_experiment_winner_choose).to receive(:call) experiment.winner = "green" end context "when has_winner state is memoized" do before { expect(experiment).to_not have_winner } it "should keep has_winner state consistent" do experiment.winner = "red" expect(experiment).to have_winner end end end describe "reset_winner" do before { experiment.winner = "green" } it "should reset the winner" do experiment.reset_winner expect(experiment.winner).to be_nil end context "when has_winner state is memoized" do before { expect(experiment).to have_winner } it "should keep has_winner state consistent" do experiment.reset_winner expect(experiment).to_not have_winner end end end describe "has_winner?" do context "with winner" do before { experiment.winner = "red" } it "returns true" do expect(experiment).to have_winner end end context "without winner" do it "returns false" do expect(experiment).to_not have_winner end end it "memoizes has_winner state" do expect(experiment).to receive(:winner).once expect(experiment).to_not have_winner expect(experiment).to_not have_winner end end describe "reset" do let(:reset_manually) { false } before do allow(Split.configuration).to receive(:reset_manually).and_return(reset_manually) experiment.save green.increment_participation green.increment_participation end it "should reset all alternatives" do experiment.winner = "green" expect(experiment.next_alternative.name).to eq("green") green.increment_participation experiment.reset expect(green.participant_count).to eq(0) expect(green.completed_count).to eq(0) end it "should reset the winner" do experiment.winner = "green" expect(experiment.next_alternative.name).to eq("green") green.increment_participation experiment.reset expect(experiment.winner).to be_nil end it "should increment the version" do expect(experiment.version).to eq(0) experiment.reset expect(experiment.version).to eq(1) end it "should call the on_experiment_reset hook" do expect(Split.configuration.on_experiment_reset).to receive(:call) experiment.reset end it "should call the on_before_experiment_reset hook" do expect(Split.configuration.on_before_experiment_reset).to receive(:call) experiment.reset end end describe "algorithm" do let(:experiment) { Split::ExperimentCatalog.find_or_create("link_color", "blue", "red", "green") } it "should use the default algorithm if none is specified" do expect(experiment.algorithm).to eq(Split.configuration.algorithm) end it "should use the user specified algorithm for this experiment if specified" do experiment.algorithm = Split::Algorithms::Whiplash expect(experiment.algorithm).to eq(Split::Algorithms::Whiplash) end end describe "#next_alternative" do context "with multiple alternatives" do let(:experiment) { Split::ExperimentCatalog.find_or_create("link_color", "blue", "red", "green") } context "with winner" do it "should always return the winner" do green = Split::Alternative.new("green", "link_color") experiment.winner = "green" expect(experiment.next_alternative.name).to eq("green") green.increment_participation expect(experiment.next_alternative.name).to eq("green") end end context "without winner" do it "should use the specified algorithm" do experiment.algorithm = Split::Algorithms::Whiplash expect(experiment.algorithm).to receive(:choose_alternative).and_return(Split::Alternative.new("green", "link_color")) expect(experiment.next_alternative.name).to eq("green") end end end context "with single alternative" do let(:experiment) { Split::ExperimentCatalog.find_or_create("link_color", "blue") } it "should always return the only alternative" do expect(experiment.next_alternative.name).to eq("blue") expect(experiment.next_alternative.name).to eq("blue") end end end describe "#cohorting_disabled?" do it "returns false when nothing has been configured" do expect(experiment.cohorting_disabled?).to eq false end it "returns true when enable_cohorting is performed" do experiment.enable_cohorting expect(experiment.cohorting_disabled?).to eq false end it "returns false when nothing has been configured" do experiment.disable_cohorting expect(experiment.cohorting_disabled?).to eq true end end describe "changing an existing experiment" do def same_but_different_alternative Split::ExperimentCatalog.find_or_create("link_color", "blue", "yellow", "orange") end it "should reset an experiment if it is loaded with different alternatives" do experiment.save blue.participant_count = 5 same_experiment = same_but_different_alternative expect(same_experiment.alternatives.map(&:name)).to eq(["blue", "yellow", "orange"]) expect(blue.participant_count).to eq(0) end it "should only reset once" do experiment.save expect(experiment.version).to eq(0) same_experiment = same_but_different_alternative expect(same_experiment.version).to eq(1) same_experiment_again = same_but_different_alternative expect(same_experiment_again.version).to eq(1) end context "when metadata is changed" do it "should increase version" do experiment.save experiment.metadata = { "foo" => "bar" } expect { experiment.save }.to change { experiment.version }.by(1) end it "does not increase version" do experiment.metadata = nil experiment.save expect { experiment.save }.to change { experiment.version }.by(0) end end context "when experiment configuration is changed" do let(:reset_manually) { false } before do experiment.save allow(Split.configuration).to receive(:reset_manually).and_return(reset_manually) green.increment_participation green.increment_participation experiment.set_alternatives_and_options(alternatives: %w(blue red green zip), goals: %w(purchase)) experiment.save end it "resets all alternatives" do expect(green.participant_count).to eq(0) expect(green.completed_count).to eq(0) end context "when reset_manually is set" do let(:reset_manually) { true } it "does not reset alternatives" do expect(green.participant_count).to eq(2) expect(green.completed_count).to eq(0) end end end end describe "alternatives passed as non-strings" do it "should throw an exception if an alternative is passed that is not a string" do expect { Split::ExperimentCatalog.find_or_create("link_color", :blue, :red) }.to raise_error(ArgumentError) expect { Split::ExperimentCatalog.find_or_create("link_enabled", true, false) }.to raise_error(ArgumentError) end end describe "specifying weights" do let(:experiment_with_weight) { Split::ExperimentCatalog.find_or_create("link_color", { "blue" => 1 }, { "red" => 2 }) } it "should work for a new experiment" do expect(experiment_with_weight.alternatives.map(&:weight)).to eq([1, 2]) end it "should work for an existing experiment" do experiment.save expect(experiment_with_weight.alternatives.map(&:weight)).to eq([1, 2]) end end describe "specifying goals" do let(:experiment) { new_experiment(["purchase"]) } context "saving experiment" do let(:same_but_different_goals) { Split::ExperimentCatalog.find_or_create({ "link_color" => ["purchase", "refund"] }, "blue", "red", "green") } before { experiment.save } it "can find existing experiment" do expect(Split::ExperimentCatalog.find("link_color").name).to eq("link_color") end it "should reset an experiment if it is loaded with different goals" do same_but_different_goals expect(Split::ExperimentCatalog.find("link_color").goals).to eq(["purchase", "refund"]) end end it "should have goals" do expect(experiment.goals).to eq(["purchase"]) end context "find or create experiment" do it "should have correct goals" do experiment = Split::ExperimentCatalog.find_or_create({ "link_color3" => ["purchase", "refund"] }, "blue", "red", "green") expect(experiment.goals).to eq(["purchase", "refund"]) experiment = Split::ExperimentCatalog.find_or_create("link_color3", "blue", "red", "green") expect(experiment.goals).to eq([]) end end end describe "beta probability calculation" do it "should return a hash with the probability of each alternative being the best" do experiment = Split::ExperimentCatalog.find_or_create("mathematicians", "bernoulli", "poisson", "lagrange") experiment.calc_winning_alternatives expect(experiment.alternative_probabilities).not_to be_nil end it "should return between 46% and 54% probability for an experiment with 2 alternatives and no data" do experiment = Split::ExperimentCatalog.find_or_create("scientists", "einstein", "bohr") experiment.calc_winning_alternatives expect(experiment.alternatives[0].p_winner).to be_within(0.04).of(0.50) end it "should calculate the probability of being the winning alternative separately for each goal", skip: true do experiment = Split::ExperimentCatalog.find_or_create({ "link_color3" => ["purchase", "refund"] }, "blue", "red", "green") goal1 = experiment.goals[0] goal2 = experiment.goals[1] experiment.alternatives.each do |alternative| alternative.participant_count = 50 alternative.set_completed_count(10, goal1) alternative.set_completed_count(15+rand(30), goal2) end experiment.calc_winning_alternatives alt = experiment.alternatives[0] p_goal1 = alt.p_winner(goal1) p_goal2 = alt.p_winner(goal2) expect(p_goal1).not_to be_within(0.04).of(p_goal2) end it "should return nil and not re-calculate probabilities if they have already been calculated today" do experiment = Split::ExperimentCatalog.find_or_create({ "link_color3" => ["purchase", "refund"] }, "blue", "red", "green") expect(experiment.calc_winning_alternatives).not_to be nil expect(experiment.calc_winning_alternatives).to be nil end end end <MSG> If the alternatives of an experiment are changed it resets the experiment and uses the new alternatives <DFF> @@ -122,5 +122,17 @@ describe Split::Experiment do experiment.next_alternative.name.should eql('green') end end -end + describe 'changing an existing experiment' do + it "should reset an experiment if it is loaded with different alternatives" do + experiment = Split::Experiment.find_or_create('link_color', 'blue', 'red', 'green') + blue = Split::Alternative.find('blue', 'link_color') + blue.participant_count = 5 + blue.save + same_experiment = Split::Experiment.find_or_create('link_color', 'blue', 'yellow', 'orange') + same_experiment.alternatives.map(&:name).should eql(['blue', 'yellow', 'orange']) + new_blue = Split::Alternative.find('blue', 'link_color') + new_blue.participant_count.should eql(0) + end + end +end \ No newline at end of file
13
If the alternatives of an experiment are changed it resets the experiment and uses the new alternatives
1
.rb
rb
mit
splitrb/split
10072140
<NME> experiment_spec.rb <BEF> # frozen_string_literal: true require "spec_helper" require "time" describe Split::Experiment do def new_experiment(goals = []) Split::Experiment.new("link_color", alternatives: ["blue", "red", "green"], goals: goals) end def alternative(color) Split::Alternative.new(color, "link_color") end let(:experiment) { new_experiment } let(:blue) { alternative("blue") } let(:green) { alternative("green") } context "with an experiment" do let(:experiment) { Split::Experiment.new("basket_text", alternatives: ["Basket", "Cart"]) } it "should have a name" do expect(experiment.name).to eq("basket_text") end it "should have alternatives" do expect(experiment.alternatives.length).to be 2 end it "should have alternatives with correct names" do expect(experiment.alternatives.collect { |a| a.name }).to eq(["Basket", "Cart"]) end it "should be resettable by default" do expect(experiment.resettable).to be_truthy end it "should save to redis" do experiment.save expect(Split.redis.exists?("basket_text")).to be true end it "should save the start time to redis" do experiment_start_time = Time.at(1372167761) expect(Time).to receive(:now).and_return(experiment_start_time) experiment.save expect(Split::ExperimentCatalog.find("basket_text").start_time).to eq(experiment_start_time) end it "should not save the start time to redis when start_manually is enabled" do expect(Split.configuration).to receive(:start_manually).and_return(true) experiment.save expect(Split::ExperimentCatalog.find("basket_text").start_time).to be_nil end it "should save the selected algorithm to redis" do experiment_algorithm = Split::Algorithms::Whiplash experiment.algorithm = experiment_algorithm experiment.save expect(Split::ExperimentCatalog.find("basket_text").algorithm).to eq(experiment_algorithm) end it "should handle having a start time stored as a string" do experiment_start_time = Time.parse("Sat Mar 03 14:01:03") expect(Time).to receive(:now).twice.and_return(experiment_start_time) experiment.save Split.redis.hset(:experiment_start_times, experiment.name, experiment_start_time.to_s) expect(Split::ExperimentCatalog.find("basket_text").start_time).to eq(experiment_start_time) end it "should handle not having a start time" do experiment_start_time = Time.parse("Sat Mar 03 14:01:03") expect(Time).to receive(:now).and_return(experiment_start_time) experiment.save Split.redis.hdel(:experiment_start_times, experiment.name) expect(Split::ExperimentCatalog.find("basket_text").start_time).to be_nil end it "should not create duplicates when saving multiple times" do experiment.save experiment.save expect(Split.redis.exists?("basket_text")).to be true expect(Split.redis.lrange("basket_text", 0, -1)).to eq(['{"Basket":1}', '{"Cart":1}']) end describe "new record?" do it "should know if it hasn't been saved yet" do expect(experiment.new_record?).to be_truthy end it "should know if it has been saved yet" do experiment.save expect(experiment.new_record?).to be_falsey end end describe "control" do it "should be the first alternative" do experiment.save expect(experiment.control.name).to eq("Basket") end end end describe "initialization" do it "should set the algorithm when passed as an option to the initializer" do experiment = Split::Experiment.new("basket_text", alternatives: ["Basket", "Cart"], algorithm: Split::Algorithms::Whiplash) expect(experiment.algorithm).to eq(Split::Algorithms::Whiplash) end it "should be possible to make an experiment not resettable" do experiment = Split::Experiment.new("basket_text", alternatives: ["Basket", "Cart"], resettable: false) expect(experiment.resettable).to be_falsey end experiment.next_alternative.name.should eql('green') end end end end describe "persistent configuration" do it "should persist resettable in redis" do experiment = Split::Experiment.new("basket_text", alternatives: ["Basket", "Cart"], resettable: false) experiment.save e = Split::ExperimentCatalog.find("basket_text") expect(e).to eq(experiment) expect(e.resettable).to be_falsey end describe "#metadata" do let(:experiment) { Split::Experiment.new("basket_text", alternatives: ["Basket", "Cart"], algorithm: Split::Algorithms::Whiplash, metadata: meta) } let(:meta) { { a: "b" } } before do experiment.save end it "should delete the key when metadata is removed" do experiment.metadata = nil experiment.save expect(Split.redis.exists?(experiment.metadata_key)).to be_falsey end context "simple hash" do let(:meta) { { "basket" => "a", "cart" => "b" } } it "should persist metadata in redis" do e = Split::ExperimentCatalog.find("basket_text") expect(e).to eq(experiment) expect(e.metadata).to eq(meta) end end context "nested hash" do let(:meta) { { "basket" => { "one" => "two" }, "cart" => "b" } } it "should persist metadata in redis" do e = Split::ExperimentCatalog.find("basket_text") expect(e).to eq(experiment) expect(e.metadata).to eq(meta) end end end it "should persist algorithm in redis" do experiment = Split::Experiment.new("basket_text", alternatives: ["Basket", "Cart"], algorithm: Split::Algorithms::Whiplash) experiment.save e = Split::ExperimentCatalog.find("basket_text") expect(e).to eq(experiment) expect(e.algorithm).to eq(Split::Algorithms::Whiplash) end it "should persist a new experiment in redis, that does not exist in the configuration file" do experiment = Split::Experiment.new("foobar", alternatives: ["tra", "la"], algorithm: Split::Algorithms::Whiplash) experiment.save e = Split::ExperimentCatalog.find("foobar") expect(e).to eq(experiment) expect(e.alternatives.collect { |a| a.name }).to eq(["tra", "la"]) end end describe "deleting" do it "should delete itself" do experiment = Split::Experiment.new("basket_text", alternatives: [ "Basket", "Cart"]) experiment.save experiment.delete expect(Split.redis.exists?("link_color")).to be false expect(Split::ExperimentCatalog.find("link_color")).to be_nil end it "should increment the version" do expect(experiment.version).to eq(0) experiment.delete expect(experiment.version).to eq(1) end it "should call the on_experiment_delete hook" do expect(Split.configuration.on_experiment_delete).to receive(:call) experiment.delete end it "should call the on_before_experiment_delete hook" do expect(Split.configuration.on_before_experiment_delete).to receive(:call) experiment.delete end it "should reset the start time if the experiment should be manually started" do Split.configuration.start_manually = true experiment.start experiment.delete expect(experiment.start_time).to be_nil end it "should default cohorting back to false" do experiment.disable_cohorting expect(experiment.cohorting_disabled?).to eq(true) experiment.delete expect(experiment.cohorting_disabled?).to eq(false) end end describe "winner" do it "should have no winner initially" do expect(experiment.winner).to be_nil end end describe "winner=" do it "should allow you to specify a winner" do experiment.save experiment.winner = "red" expect(experiment.winner.name).to eq("red") end it "should call the on_experiment_winner_choose hook" do expect(Split.configuration.on_experiment_winner_choose).to receive(:call) experiment.winner = "green" end context "when has_winner state is memoized" do before { expect(experiment).to_not have_winner } it "should keep has_winner state consistent" do experiment.winner = "red" expect(experiment).to have_winner end end end describe "reset_winner" do before { experiment.winner = "green" } it "should reset the winner" do experiment.reset_winner expect(experiment.winner).to be_nil end context "when has_winner state is memoized" do before { expect(experiment).to have_winner } it "should keep has_winner state consistent" do experiment.reset_winner expect(experiment).to_not have_winner end end end describe "has_winner?" do context "with winner" do before { experiment.winner = "red" } it "returns true" do expect(experiment).to have_winner end end context "without winner" do it "returns false" do expect(experiment).to_not have_winner end end it "memoizes has_winner state" do expect(experiment).to receive(:winner).once expect(experiment).to_not have_winner expect(experiment).to_not have_winner end end describe "reset" do let(:reset_manually) { false } before do allow(Split.configuration).to receive(:reset_manually).and_return(reset_manually) experiment.save green.increment_participation green.increment_participation end it "should reset all alternatives" do experiment.winner = "green" expect(experiment.next_alternative.name).to eq("green") green.increment_participation experiment.reset expect(green.participant_count).to eq(0) expect(green.completed_count).to eq(0) end it "should reset the winner" do experiment.winner = "green" expect(experiment.next_alternative.name).to eq("green") green.increment_participation experiment.reset expect(experiment.winner).to be_nil end it "should increment the version" do expect(experiment.version).to eq(0) experiment.reset expect(experiment.version).to eq(1) end it "should call the on_experiment_reset hook" do expect(Split.configuration.on_experiment_reset).to receive(:call) experiment.reset end it "should call the on_before_experiment_reset hook" do expect(Split.configuration.on_before_experiment_reset).to receive(:call) experiment.reset end end describe "algorithm" do let(:experiment) { Split::ExperimentCatalog.find_or_create("link_color", "blue", "red", "green") } it "should use the default algorithm if none is specified" do expect(experiment.algorithm).to eq(Split.configuration.algorithm) end it "should use the user specified algorithm for this experiment if specified" do experiment.algorithm = Split::Algorithms::Whiplash expect(experiment.algorithm).to eq(Split::Algorithms::Whiplash) end end describe "#next_alternative" do context "with multiple alternatives" do let(:experiment) { Split::ExperimentCatalog.find_or_create("link_color", "blue", "red", "green") } context "with winner" do it "should always return the winner" do green = Split::Alternative.new("green", "link_color") experiment.winner = "green" expect(experiment.next_alternative.name).to eq("green") green.increment_participation expect(experiment.next_alternative.name).to eq("green") end end context "without winner" do it "should use the specified algorithm" do experiment.algorithm = Split::Algorithms::Whiplash expect(experiment.algorithm).to receive(:choose_alternative).and_return(Split::Alternative.new("green", "link_color")) expect(experiment.next_alternative.name).to eq("green") end end end context "with single alternative" do let(:experiment) { Split::ExperimentCatalog.find_or_create("link_color", "blue") } it "should always return the only alternative" do expect(experiment.next_alternative.name).to eq("blue") expect(experiment.next_alternative.name).to eq("blue") end end end describe "#cohorting_disabled?" do it "returns false when nothing has been configured" do expect(experiment.cohorting_disabled?).to eq false end it "returns true when enable_cohorting is performed" do experiment.enable_cohorting expect(experiment.cohorting_disabled?).to eq false end it "returns false when nothing has been configured" do experiment.disable_cohorting expect(experiment.cohorting_disabled?).to eq true end end describe "changing an existing experiment" do def same_but_different_alternative Split::ExperimentCatalog.find_or_create("link_color", "blue", "yellow", "orange") end it "should reset an experiment if it is loaded with different alternatives" do experiment.save blue.participant_count = 5 same_experiment = same_but_different_alternative expect(same_experiment.alternatives.map(&:name)).to eq(["blue", "yellow", "orange"]) expect(blue.participant_count).to eq(0) end it "should only reset once" do experiment.save expect(experiment.version).to eq(0) same_experiment = same_but_different_alternative expect(same_experiment.version).to eq(1) same_experiment_again = same_but_different_alternative expect(same_experiment_again.version).to eq(1) end context "when metadata is changed" do it "should increase version" do experiment.save experiment.metadata = { "foo" => "bar" } expect { experiment.save }.to change { experiment.version }.by(1) end it "does not increase version" do experiment.metadata = nil experiment.save expect { experiment.save }.to change { experiment.version }.by(0) end end context "when experiment configuration is changed" do let(:reset_manually) { false } before do experiment.save allow(Split.configuration).to receive(:reset_manually).and_return(reset_manually) green.increment_participation green.increment_participation experiment.set_alternatives_and_options(alternatives: %w(blue red green zip), goals: %w(purchase)) experiment.save end it "resets all alternatives" do expect(green.participant_count).to eq(0) expect(green.completed_count).to eq(0) end context "when reset_manually is set" do let(:reset_manually) { true } it "does not reset alternatives" do expect(green.participant_count).to eq(2) expect(green.completed_count).to eq(0) end end end end describe "alternatives passed as non-strings" do it "should throw an exception if an alternative is passed that is not a string" do expect { Split::ExperimentCatalog.find_or_create("link_color", :blue, :red) }.to raise_error(ArgumentError) expect { Split::ExperimentCatalog.find_or_create("link_enabled", true, false) }.to raise_error(ArgumentError) end end describe "specifying weights" do let(:experiment_with_weight) { Split::ExperimentCatalog.find_or_create("link_color", { "blue" => 1 }, { "red" => 2 }) } it "should work for a new experiment" do expect(experiment_with_weight.alternatives.map(&:weight)).to eq([1, 2]) end it "should work for an existing experiment" do experiment.save expect(experiment_with_weight.alternatives.map(&:weight)).to eq([1, 2]) end end describe "specifying goals" do let(:experiment) { new_experiment(["purchase"]) } context "saving experiment" do let(:same_but_different_goals) { Split::ExperimentCatalog.find_or_create({ "link_color" => ["purchase", "refund"] }, "blue", "red", "green") } before { experiment.save } it "can find existing experiment" do expect(Split::ExperimentCatalog.find("link_color").name).to eq("link_color") end it "should reset an experiment if it is loaded with different goals" do same_but_different_goals expect(Split::ExperimentCatalog.find("link_color").goals).to eq(["purchase", "refund"]) end end it "should have goals" do expect(experiment.goals).to eq(["purchase"]) end context "find or create experiment" do it "should have correct goals" do experiment = Split::ExperimentCatalog.find_or_create({ "link_color3" => ["purchase", "refund"] }, "blue", "red", "green") expect(experiment.goals).to eq(["purchase", "refund"]) experiment = Split::ExperimentCatalog.find_or_create("link_color3", "blue", "red", "green") expect(experiment.goals).to eq([]) end end end describe "beta probability calculation" do it "should return a hash with the probability of each alternative being the best" do experiment = Split::ExperimentCatalog.find_or_create("mathematicians", "bernoulli", "poisson", "lagrange") experiment.calc_winning_alternatives expect(experiment.alternative_probabilities).not_to be_nil end it "should return between 46% and 54% probability for an experiment with 2 alternatives and no data" do experiment = Split::ExperimentCatalog.find_or_create("scientists", "einstein", "bohr") experiment.calc_winning_alternatives expect(experiment.alternatives[0].p_winner).to be_within(0.04).of(0.50) end it "should calculate the probability of being the winning alternative separately for each goal", skip: true do experiment = Split::ExperimentCatalog.find_or_create({ "link_color3" => ["purchase", "refund"] }, "blue", "red", "green") goal1 = experiment.goals[0] goal2 = experiment.goals[1] experiment.alternatives.each do |alternative| alternative.participant_count = 50 alternative.set_completed_count(10, goal1) alternative.set_completed_count(15+rand(30), goal2) end experiment.calc_winning_alternatives alt = experiment.alternatives[0] p_goal1 = alt.p_winner(goal1) p_goal2 = alt.p_winner(goal2) expect(p_goal1).not_to be_within(0.04).of(p_goal2) end it "should return nil and not re-calculate probabilities if they have already been calculated today" do experiment = Split::ExperimentCatalog.find_or_create({ "link_color3" => ["purchase", "refund"] }, "blue", "red", "green") expect(experiment.calc_winning_alternatives).not_to be nil expect(experiment.calc_winning_alternatives).to be nil end end end <MSG> If the alternatives of an experiment are changed it resets the experiment and uses the new alternatives <DFF> @@ -122,5 +122,17 @@ describe Split::Experiment do experiment.next_alternative.name.should eql('green') end end -end + describe 'changing an existing experiment' do + it "should reset an experiment if it is loaded with different alternatives" do + experiment = Split::Experiment.find_or_create('link_color', 'blue', 'red', 'green') + blue = Split::Alternative.find('blue', 'link_color') + blue.participant_count = 5 + blue.save + same_experiment = Split::Experiment.find_or_create('link_color', 'blue', 'yellow', 'orange') + same_experiment.alternatives.map(&:name).should eql(['blue', 'yellow', 'orange']) + new_blue = Split::Alternative.find('blue', 'link_color') + new_blue.participant_count.should eql(0) + end + end +end \ No newline at end of file
13
If the alternatives of an experiment are changed it resets the experiment and uses the new alternatives
1
.rb
rb
mit
splitrb/split
10072141
<NME> experiment_spec.rb <BEF> # frozen_string_literal: true require "spec_helper" require "time" describe Split::Experiment do def new_experiment(goals = []) Split::Experiment.new("link_color", alternatives: ["blue", "red", "green"], goals: goals) end def alternative(color) Split::Alternative.new(color, "link_color") end let(:experiment) { new_experiment } let(:blue) { alternative("blue") } let(:green) { alternative("green") } context "with an experiment" do let(:experiment) { Split::Experiment.new("basket_text", alternatives: ["Basket", "Cart"]) } it "should have a name" do expect(experiment.name).to eq("basket_text") end it "should have alternatives" do expect(experiment.alternatives.length).to be 2 end it "should have alternatives with correct names" do expect(experiment.alternatives.collect { |a| a.name }).to eq(["Basket", "Cart"]) end it "should be resettable by default" do expect(experiment.resettable).to be_truthy end it "should save to redis" do experiment.save expect(Split.redis.exists?("basket_text")).to be true end it "should save the start time to redis" do experiment_start_time = Time.at(1372167761) expect(Time).to receive(:now).and_return(experiment_start_time) experiment.save expect(Split::ExperimentCatalog.find("basket_text").start_time).to eq(experiment_start_time) end it "should not save the start time to redis when start_manually is enabled" do expect(Split.configuration).to receive(:start_manually).and_return(true) experiment.save expect(Split::ExperimentCatalog.find("basket_text").start_time).to be_nil end it "should save the selected algorithm to redis" do experiment_algorithm = Split::Algorithms::Whiplash experiment.algorithm = experiment_algorithm experiment.save expect(Split::ExperimentCatalog.find("basket_text").algorithm).to eq(experiment_algorithm) end it "should handle having a start time stored as a string" do experiment_start_time = Time.parse("Sat Mar 03 14:01:03") expect(Time).to receive(:now).twice.and_return(experiment_start_time) experiment.save Split.redis.hset(:experiment_start_times, experiment.name, experiment_start_time.to_s) expect(Split::ExperimentCatalog.find("basket_text").start_time).to eq(experiment_start_time) end it "should handle not having a start time" do experiment_start_time = Time.parse("Sat Mar 03 14:01:03") expect(Time).to receive(:now).and_return(experiment_start_time) experiment.save Split.redis.hdel(:experiment_start_times, experiment.name) expect(Split::ExperimentCatalog.find("basket_text").start_time).to be_nil end it "should not create duplicates when saving multiple times" do experiment.save experiment.save expect(Split.redis.exists?("basket_text")).to be true expect(Split.redis.lrange("basket_text", 0, -1)).to eq(['{"Basket":1}', '{"Cart":1}']) end describe "new record?" do it "should know if it hasn't been saved yet" do expect(experiment.new_record?).to be_truthy end it "should know if it has been saved yet" do experiment.save expect(experiment.new_record?).to be_falsey end end describe "control" do it "should be the first alternative" do experiment.save expect(experiment.control.name).to eq("Basket") end end end describe "initialization" do it "should set the algorithm when passed as an option to the initializer" do experiment = Split::Experiment.new("basket_text", alternatives: ["Basket", "Cart"], algorithm: Split::Algorithms::Whiplash) expect(experiment.algorithm).to eq(Split::Algorithms::Whiplash) end it "should be possible to make an experiment not resettable" do experiment = Split::Experiment.new("basket_text", alternatives: ["Basket", "Cart"], resettable: false) expect(experiment.resettable).to be_falsey end experiment.next_alternative.name.should eql('green') end end end end describe "persistent configuration" do it "should persist resettable in redis" do experiment = Split::Experiment.new("basket_text", alternatives: ["Basket", "Cart"], resettable: false) experiment.save e = Split::ExperimentCatalog.find("basket_text") expect(e).to eq(experiment) expect(e.resettable).to be_falsey end describe "#metadata" do let(:experiment) { Split::Experiment.new("basket_text", alternatives: ["Basket", "Cart"], algorithm: Split::Algorithms::Whiplash, metadata: meta) } let(:meta) { { a: "b" } } before do experiment.save end it "should delete the key when metadata is removed" do experiment.metadata = nil experiment.save expect(Split.redis.exists?(experiment.metadata_key)).to be_falsey end context "simple hash" do let(:meta) { { "basket" => "a", "cart" => "b" } } it "should persist metadata in redis" do e = Split::ExperimentCatalog.find("basket_text") expect(e).to eq(experiment) expect(e.metadata).to eq(meta) end end context "nested hash" do let(:meta) { { "basket" => { "one" => "two" }, "cart" => "b" } } it "should persist metadata in redis" do e = Split::ExperimentCatalog.find("basket_text") expect(e).to eq(experiment) expect(e.metadata).to eq(meta) end end end it "should persist algorithm in redis" do experiment = Split::Experiment.new("basket_text", alternatives: ["Basket", "Cart"], algorithm: Split::Algorithms::Whiplash) experiment.save e = Split::ExperimentCatalog.find("basket_text") expect(e).to eq(experiment) expect(e.algorithm).to eq(Split::Algorithms::Whiplash) end it "should persist a new experiment in redis, that does not exist in the configuration file" do experiment = Split::Experiment.new("foobar", alternatives: ["tra", "la"], algorithm: Split::Algorithms::Whiplash) experiment.save e = Split::ExperimentCatalog.find("foobar") expect(e).to eq(experiment) expect(e.alternatives.collect { |a| a.name }).to eq(["tra", "la"]) end end describe "deleting" do it "should delete itself" do experiment = Split::Experiment.new("basket_text", alternatives: [ "Basket", "Cart"]) experiment.save experiment.delete expect(Split.redis.exists?("link_color")).to be false expect(Split::ExperimentCatalog.find("link_color")).to be_nil end it "should increment the version" do expect(experiment.version).to eq(0) experiment.delete expect(experiment.version).to eq(1) end it "should call the on_experiment_delete hook" do expect(Split.configuration.on_experiment_delete).to receive(:call) experiment.delete end it "should call the on_before_experiment_delete hook" do expect(Split.configuration.on_before_experiment_delete).to receive(:call) experiment.delete end it "should reset the start time if the experiment should be manually started" do Split.configuration.start_manually = true experiment.start experiment.delete expect(experiment.start_time).to be_nil end it "should default cohorting back to false" do experiment.disable_cohorting expect(experiment.cohorting_disabled?).to eq(true) experiment.delete expect(experiment.cohorting_disabled?).to eq(false) end end describe "winner" do it "should have no winner initially" do expect(experiment.winner).to be_nil end end describe "winner=" do it "should allow you to specify a winner" do experiment.save experiment.winner = "red" expect(experiment.winner.name).to eq("red") end it "should call the on_experiment_winner_choose hook" do expect(Split.configuration.on_experiment_winner_choose).to receive(:call) experiment.winner = "green" end context "when has_winner state is memoized" do before { expect(experiment).to_not have_winner } it "should keep has_winner state consistent" do experiment.winner = "red" expect(experiment).to have_winner end end end describe "reset_winner" do before { experiment.winner = "green" } it "should reset the winner" do experiment.reset_winner expect(experiment.winner).to be_nil end context "when has_winner state is memoized" do before { expect(experiment).to have_winner } it "should keep has_winner state consistent" do experiment.reset_winner expect(experiment).to_not have_winner end end end describe "has_winner?" do context "with winner" do before { experiment.winner = "red" } it "returns true" do expect(experiment).to have_winner end end context "without winner" do it "returns false" do expect(experiment).to_not have_winner end end it "memoizes has_winner state" do expect(experiment).to receive(:winner).once expect(experiment).to_not have_winner expect(experiment).to_not have_winner end end describe "reset" do let(:reset_manually) { false } before do allow(Split.configuration).to receive(:reset_manually).and_return(reset_manually) experiment.save green.increment_participation green.increment_participation end it "should reset all alternatives" do experiment.winner = "green" expect(experiment.next_alternative.name).to eq("green") green.increment_participation experiment.reset expect(green.participant_count).to eq(0) expect(green.completed_count).to eq(0) end it "should reset the winner" do experiment.winner = "green" expect(experiment.next_alternative.name).to eq("green") green.increment_participation experiment.reset expect(experiment.winner).to be_nil end it "should increment the version" do expect(experiment.version).to eq(0) experiment.reset expect(experiment.version).to eq(1) end it "should call the on_experiment_reset hook" do expect(Split.configuration.on_experiment_reset).to receive(:call) experiment.reset end it "should call the on_before_experiment_reset hook" do expect(Split.configuration.on_before_experiment_reset).to receive(:call) experiment.reset end end describe "algorithm" do let(:experiment) { Split::ExperimentCatalog.find_or_create("link_color", "blue", "red", "green") } it "should use the default algorithm if none is specified" do expect(experiment.algorithm).to eq(Split.configuration.algorithm) end it "should use the user specified algorithm for this experiment if specified" do experiment.algorithm = Split::Algorithms::Whiplash expect(experiment.algorithm).to eq(Split::Algorithms::Whiplash) end end describe "#next_alternative" do context "with multiple alternatives" do let(:experiment) { Split::ExperimentCatalog.find_or_create("link_color", "blue", "red", "green") } context "with winner" do it "should always return the winner" do green = Split::Alternative.new("green", "link_color") experiment.winner = "green" expect(experiment.next_alternative.name).to eq("green") green.increment_participation expect(experiment.next_alternative.name).to eq("green") end end context "without winner" do it "should use the specified algorithm" do experiment.algorithm = Split::Algorithms::Whiplash expect(experiment.algorithm).to receive(:choose_alternative).and_return(Split::Alternative.new("green", "link_color")) expect(experiment.next_alternative.name).to eq("green") end end end context "with single alternative" do let(:experiment) { Split::ExperimentCatalog.find_or_create("link_color", "blue") } it "should always return the only alternative" do expect(experiment.next_alternative.name).to eq("blue") expect(experiment.next_alternative.name).to eq("blue") end end end describe "#cohorting_disabled?" do it "returns false when nothing has been configured" do expect(experiment.cohorting_disabled?).to eq false end it "returns true when enable_cohorting is performed" do experiment.enable_cohorting expect(experiment.cohorting_disabled?).to eq false end it "returns false when nothing has been configured" do experiment.disable_cohorting expect(experiment.cohorting_disabled?).to eq true end end describe "changing an existing experiment" do def same_but_different_alternative Split::ExperimentCatalog.find_or_create("link_color", "blue", "yellow", "orange") end it "should reset an experiment if it is loaded with different alternatives" do experiment.save blue.participant_count = 5 same_experiment = same_but_different_alternative expect(same_experiment.alternatives.map(&:name)).to eq(["blue", "yellow", "orange"]) expect(blue.participant_count).to eq(0) end it "should only reset once" do experiment.save expect(experiment.version).to eq(0) same_experiment = same_but_different_alternative expect(same_experiment.version).to eq(1) same_experiment_again = same_but_different_alternative expect(same_experiment_again.version).to eq(1) end context "when metadata is changed" do it "should increase version" do experiment.save experiment.metadata = { "foo" => "bar" } expect { experiment.save }.to change { experiment.version }.by(1) end it "does not increase version" do experiment.metadata = nil experiment.save expect { experiment.save }.to change { experiment.version }.by(0) end end context "when experiment configuration is changed" do let(:reset_manually) { false } before do experiment.save allow(Split.configuration).to receive(:reset_manually).and_return(reset_manually) green.increment_participation green.increment_participation experiment.set_alternatives_and_options(alternatives: %w(blue red green zip), goals: %w(purchase)) experiment.save end it "resets all alternatives" do expect(green.participant_count).to eq(0) expect(green.completed_count).to eq(0) end context "when reset_manually is set" do let(:reset_manually) { true } it "does not reset alternatives" do expect(green.participant_count).to eq(2) expect(green.completed_count).to eq(0) end end end end describe "alternatives passed as non-strings" do it "should throw an exception if an alternative is passed that is not a string" do expect { Split::ExperimentCatalog.find_or_create("link_color", :blue, :red) }.to raise_error(ArgumentError) expect { Split::ExperimentCatalog.find_or_create("link_enabled", true, false) }.to raise_error(ArgumentError) end end describe "specifying weights" do let(:experiment_with_weight) { Split::ExperimentCatalog.find_or_create("link_color", { "blue" => 1 }, { "red" => 2 }) } it "should work for a new experiment" do expect(experiment_with_weight.alternatives.map(&:weight)).to eq([1, 2]) end it "should work for an existing experiment" do experiment.save expect(experiment_with_weight.alternatives.map(&:weight)).to eq([1, 2]) end end describe "specifying goals" do let(:experiment) { new_experiment(["purchase"]) } context "saving experiment" do let(:same_but_different_goals) { Split::ExperimentCatalog.find_or_create({ "link_color" => ["purchase", "refund"] }, "blue", "red", "green") } before { experiment.save } it "can find existing experiment" do expect(Split::ExperimentCatalog.find("link_color").name).to eq("link_color") end it "should reset an experiment if it is loaded with different goals" do same_but_different_goals expect(Split::ExperimentCatalog.find("link_color").goals).to eq(["purchase", "refund"]) end end it "should have goals" do expect(experiment.goals).to eq(["purchase"]) end context "find or create experiment" do it "should have correct goals" do experiment = Split::ExperimentCatalog.find_or_create({ "link_color3" => ["purchase", "refund"] }, "blue", "red", "green") expect(experiment.goals).to eq(["purchase", "refund"]) experiment = Split::ExperimentCatalog.find_or_create("link_color3", "blue", "red", "green") expect(experiment.goals).to eq([]) end end end describe "beta probability calculation" do it "should return a hash with the probability of each alternative being the best" do experiment = Split::ExperimentCatalog.find_or_create("mathematicians", "bernoulli", "poisson", "lagrange") experiment.calc_winning_alternatives expect(experiment.alternative_probabilities).not_to be_nil end it "should return between 46% and 54% probability for an experiment with 2 alternatives and no data" do experiment = Split::ExperimentCatalog.find_or_create("scientists", "einstein", "bohr") experiment.calc_winning_alternatives expect(experiment.alternatives[0].p_winner).to be_within(0.04).of(0.50) end it "should calculate the probability of being the winning alternative separately for each goal", skip: true do experiment = Split::ExperimentCatalog.find_or_create({ "link_color3" => ["purchase", "refund"] }, "blue", "red", "green") goal1 = experiment.goals[0] goal2 = experiment.goals[1] experiment.alternatives.each do |alternative| alternative.participant_count = 50 alternative.set_completed_count(10, goal1) alternative.set_completed_count(15+rand(30), goal2) end experiment.calc_winning_alternatives alt = experiment.alternatives[0] p_goal1 = alt.p_winner(goal1) p_goal2 = alt.p_winner(goal2) expect(p_goal1).not_to be_within(0.04).of(p_goal2) end it "should return nil and not re-calculate probabilities if they have already been calculated today" do experiment = Split::ExperimentCatalog.find_or_create({ "link_color3" => ["purchase", "refund"] }, "blue", "red", "green") expect(experiment.calc_winning_alternatives).not_to be nil expect(experiment.calc_winning_alternatives).to be nil end end end <MSG> If the alternatives of an experiment are changed it resets the experiment and uses the new alternatives <DFF> @@ -122,5 +122,17 @@ describe Split::Experiment do experiment.next_alternative.name.should eql('green') end end -end + describe 'changing an existing experiment' do + it "should reset an experiment if it is loaded with different alternatives" do + experiment = Split::Experiment.find_or_create('link_color', 'blue', 'red', 'green') + blue = Split::Alternative.find('blue', 'link_color') + blue.participant_count = 5 + blue.save + same_experiment = Split::Experiment.find_or_create('link_color', 'blue', 'yellow', 'orange') + same_experiment.alternatives.map(&:name).should eql(['blue', 'yellow', 'orange']) + new_blue = Split::Alternative.find('blue', 'link_color') + new_blue.participant_count.should eql(0) + end + end +end \ No newline at end of file
13
If the alternatives of an experiment are changed it resets the experiment and uses the new alternatives
1
.rb
rb
mit
splitrb/split
10072142
<NME> AUTHORS <BEF> Ask Solem <askh@opera.com> Rune Halvorsen <runeh@opera.com> Russell Sim <russell.sim@gmail.com> Brian Rosner <brosner@gmail.com> Sverre Johansen <sverre.johansen@gmail.com> Bo Shi <bs@alum.mit.edu> Carl Meyer <carl@dirtcircle.com> Vinícius das Chagas Silva <vinimaster@gmail.com> Vanderson Mota dos Santos <vanderson.mota@gmail.com> Stefan Foulis <stefan.foulis@gmail.com> Michael Richardson <michael@michaelrichardson.me> Halldór Rúnarsson <halldor89@gmail.com> Brent Tubbs <brent.tubbs@gmail.com> David Cramer <dcramer@gmail.com> <MSG> Added Hugo Lopes Tavares (hugobr) to AUTHORS <DFF> @@ -2,3 +2,4 @@ Ask Solem <askh@opera.com> Rune Halvorsen <runeh@opera.com> Russell Sim <russell.sim@gmail.com> Brian Rosner <brosner@gmail.com> +Hugo Lopes Tavares <hltbra@gmail.com>
1
Added Hugo Lopes Tavares (hugobr) to AUTHORS
0
AUTHORS
bsd-3-clause
ask/chishop
10072143
<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, rawValue: '10', unit: '', start: 1, end: 3 } ]); deepEqual(tokenize('p-10'), [ { type: 'Literal', value: 'p', start: 0, end: 1 }, { 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, 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, rawValue: '-10', unit: '', start: 1, end: 4 }, { type: 'Operator', operator: '-', start: 4, end: 5 }, { 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, rawValue: '-10', unit: '', start: 1, end: 4 }, { type: 'Operator', operator: '-', start: 4, end: 5 }, { 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, rawValue: '-10', unit: '', start: 1, end: 4 }, { type: 'Operator', operator: '-', start: 4, end: 5 }, { type: 'NumberValue', value: 20, rawValue: '20', unit: '', start: 5, end: 7 }, { type: 'Operator', operator: '-', start: 7, end: 8 }, { 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: 'Operator', operator: '-', start: 5, end: 6 }, { type: 'NumberValue', value: 20, unit: '', start: 6, 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: 'Operator', operator: '-', start: 5, end: 6 }, { type: 'NumberValue', value: 20, unit: '', start: 6, 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, rawValue: '.5', unit: '', start: 1, end: 3 } ]); deepEqual(tokenize('p-.5'), [ { type: 'Literal', value: 'p', start: 0, end: 1 }, { 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, 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, rawValue: '.1', unit: '', start: 1, end: 3 }, { type: 'Operator', operator: '-', start: 3, end: 4 }, { 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, rawValue: '.1', unit: '', start: 1, end: 3 }, { type: 'Operator', operator: '-', start: 3, end: 4 }, { 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, rawValue: '10', unit: '', start: 0, end: 2 }, ]); deepEqual(tokenize('.1'), [ { type: 'NumberValue', value: 0.1, rawValue: '.1', unit: '', start: 0, end: 2 }, ]); // NB: now dot should be a part of literal // 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 } ]); deepEqual(tokenize('m-abc'), [ { type: 'Literal', value: 'm', start: 0, end: 1 }, { type: 'Operator', operator: '-', start: 1, end: 2 }, { type: 'Literal', value: 'abc', start: 2, end: 5 } ]); deepEqual(tokenize('m-a0'), [ { 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 } ]); 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 } ]); }); it('arguments', () => { deepEqual(tokenize('lg(top, "red, black", rgb(0, 0, 0) 10%)'), [ { type: 'Literal', value: 'lg', start: 0, end: 2 }, { type: 'Bracket', open: true, start: 2, end: 3 }, { type: 'Literal', value: 'top', start: 3, end: 6 }, { type: 'Operator', operator: ',', start: 6, end: 7 }, { type: 'WhiteSpace', start: 7, end: 8 }, { type: 'StringValue', value: 'red, black', quote: 'double', start: 8, end: 20 }, { type: 'Operator', operator: ',', start: 20, end: 21 }, { 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, rawValue: '0', unit: '', start: 26, end: 27 }, { 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 } ]); }); it('important', () => { deepEqual(tokenize('!'), [ { type: 'Operator', operator: '!', start: 0, end: 1 } ]); deepEqual(tokenize('p!'), [ { type: 'Literal', value: 'p', start: 0, end: 1 }, { type: 'Operator', operator: '!', start: 1, end: 2 } ]); deepEqual(tokenize('p10!'), [ { type: 'Literal', value: 'p', start: 0, end: 1 }, { type: 'NumberValue', value: 10, rawValue: '10', unit: '', start: 1, end: 3 }, { type: 'Operator', operator: '!', start: 3, end: 4 } deepEqual(tokenize('bd#fc0-1'), [ { 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: 'NumberValue', value: -1, unit: '', start: 6, end: 8 } ]); deepEqual(tokenize('p0+m0'), [ { type: 'Literal', value: 's', start: 4, end: 5 }, { type: 'ColorValue', r: 255, g: 204, b: 0, a: 1, raw: 'fc0', start: 5, end: 9 } ]); deepEqual(tokenize('bd#fc0-1'), [ { 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, rawValue: '1', unit: '', start: 7, end: 8 } ]); 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: 'Literal', value: 'm', start: 3, end: 4 }, { 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, 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 }, ]); }); it('embedded variables', () => { deepEqual(tokenize('foo$bar'), [ { type: 'Literal', value: 'foo', start: 0, end: 3 }, { type: 'Literal', value: '$bar', start: 3, end: 7 } ]); 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> Working implementation of CSS parser <DFF> @@ -45,8 +45,7 @@ describe('Tokenizer', () => { 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: 'Operator', operator: '-', start: 5, end: 6 }, - { type: 'NumberValue', value: 20, unit: '', start: 6, end: 8 }, + { 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 } ]); @@ -54,8 +53,7 @@ describe('Tokenizer', () => { deepEqual(tokenize('p-10%-20--30'), [ { type: 'Literal', value: 'p', start: 0, end: 1 }, { type: 'NumberValue', value: -10, unit: '%', start: 1, end: 5 }, - { type: 'Operator', operator: '-', start: 5, end: 6 }, - { type: 'NumberValue', value: 20, unit: '', start: 6, end: 8 }, + { 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 } ]); @@ -246,7 +244,8 @@ describe('Tokenizer', () => { deepEqual(tokenize('bd#fc0-1'), [ { 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: 'NumberValue', value: -1, unit: '', start: 6, end: 8 } + { type: 'Operator', operator: '-', start: 6, end: 7 }, + { type: 'NumberValue', value: 1, unit: '', start: 7, end: 8 } ]); deepEqual(tokenize('p0+m0'), [
4
Working implementation of CSS parser
5
.ts
ts
mit
emmetio/emmet
10072144
<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, rawValue: '10', unit: '', start: 1, end: 3 } ]); deepEqual(tokenize('p-10'), [ { type: 'Literal', value: 'p', start: 0, end: 1 }, { 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, 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, rawValue: '-10', unit: '', start: 1, end: 4 }, { type: 'Operator', operator: '-', start: 4, end: 5 }, { 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, rawValue: '-10', unit: '', start: 1, end: 4 }, { type: 'Operator', operator: '-', start: 4, end: 5 }, { 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, rawValue: '-10', unit: '', start: 1, end: 4 }, { type: 'Operator', operator: '-', start: 4, end: 5 }, { type: 'NumberValue', value: 20, rawValue: '20', unit: '', start: 5, end: 7 }, { type: 'Operator', operator: '-', start: 7, end: 8 }, { 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: 'Operator', operator: '-', start: 5, end: 6 }, { type: 'NumberValue', value: 20, unit: '', start: 6, 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: 'Operator', operator: '-', start: 5, end: 6 }, { type: 'NumberValue', value: 20, unit: '', start: 6, 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, rawValue: '.5', unit: '', start: 1, end: 3 } ]); deepEqual(tokenize('p-.5'), [ { type: 'Literal', value: 'p', start: 0, end: 1 }, { 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, 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, rawValue: '.1', unit: '', start: 1, end: 3 }, { type: 'Operator', operator: '-', start: 3, end: 4 }, { 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, rawValue: '.1', unit: '', start: 1, end: 3 }, { type: 'Operator', operator: '-', start: 3, end: 4 }, { 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, rawValue: '10', unit: '', start: 0, end: 2 }, ]); deepEqual(tokenize('.1'), [ { type: 'NumberValue', value: 0.1, rawValue: '.1', unit: '', start: 0, end: 2 }, ]); // NB: now dot should be a part of literal // 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 } ]); deepEqual(tokenize('m-abc'), [ { type: 'Literal', value: 'm', start: 0, end: 1 }, { type: 'Operator', operator: '-', start: 1, end: 2 }, { type: 'Literal', value: 'abc', start: 2, end: 5 } ]); deepEqual(tokenize('m-a0'), [ { 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 } ]); 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 } ]); }); it('arguments', () => { deepEqual(tokenize('lg(top, "red, black", rgb(0, 0, 0) 10%)'), [ { type: 'Literal', value: 'lg', start: 0, end: 2 }, { type: 'Bracket', open: true, start: 2, end: 3 }, { type: 'Literal', value: 'top', start: 3, end: 6 }, { type: 'Operator', operator: ',', start: 6, end: 7 }, { type: 'WhiteSpace', start: 7, end: 8 }, { type: 'StringValue', value: 'red, black', quote: 'double', start: 8, end: 20 }, { type: 'Operator', operator: ',', start: 20, end: 21 }, { 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, rawValue: '0', unit: '', start: 26, end: 27 }, { 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 } ]); }); it('important', () => { deepEqual(tokenize('!'), [ { type: 'Operator', operator: '!', start: 0, end: 1 } ]); deepEqual(tokenize('p!'), [ { type: 'Literal', value: 'p', start: 0, end: 1 }, { type: 'Operator', operator: '!', start: 1, end: 2 } ]); deepEqual(tokenize('p10!'), [ { type: 'Literal', value: 'p', start: 0, end: 1 }, { type: 'NumberValue', value: 10, rawValue: '10', unit: '', start: 1, end: 3 }, { type: 'Operator', operator: '!', start: 3, end: 4 } deepEqual(tokenize('bd#fc0-1'), [ { 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: 'NumberValue', value: -1, unit: '', start: 6, end: 8 } ]); deepEqual(tokenize('p0+m0'), [ { type: 'Literal', value: 's', start: 4, end: 5 }, { type: 'ColorValue', r: 255, g: 204, b: 0, a: 1, raw: 'fc0', start: 5, end: 9 } ]); deepEqual(tokenize('bd#fc0-1'), [ { 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, rawValue: '1', unit: '', start: 7, end: 8 } ]); 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: 'Literal', value: 'm', start: 3, end: 4 }, { 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, 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 }, ]); }); it('embedded variables', () => { deepEqual(tokenize('foo$bar'), [ { type: 'Literal', value: 'foo', start: 0, end: 3 }, { type: 'Literal', value: '$bar', start: 3, end: 7 } ]); 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> Working implementation of CSS parser <DFF> @@ -45,8 +45,7 @@ describe('Tokenizer', () => { 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: 'Operator', operator: '-', start: 5, end: 6 }, - { type: 'NumberValue', value: 20, unit: '', start: 6, end: 8 }, + { 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 } ]); @@ -54,8 +53,7 @@ describe('Tokenizer', () => { deepEqual(tokenize('p-10%-20--30'), [ { type: 'Literal', value: 'p', start: 0, end: 1 }, { type: 'NumberValue', value: -10, unit: '%', start: 1, end: 5 }, - { type: 'Operator', operator: '-', start: 5, end: 6 }, - { type: 'NumberValue', value: 20, unit: '', start: 6, end: 8 }, + { 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 } ]); @@ -246,7 +244,8 @@ describe('Tokenizer', () => { deepEqual(tokenize('bd#fc0-1'), [ { 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: 'NumberValue', value: -1, unit: '', start: 6, end: 8 } + { type: 'Operator', operator: '-', start: 6, end: 7 }, + { type: 'NumberValue', value: 1, unit: '', start: 7, end: 8 } ]); deepEqual(tokenize('p0+m0'), [
4
Working implementation of CSS parser
5
.ts
ts
mit
emmetio/emmet
10072145
<NME> index.erb <BEF> <% if @experiments.any? %> <p class="intro">The list below contains all the registered experiments along with the number of test participants, completed and conversion rate currently in the system.</p> <div class="dashboard-controls"> <input type="text" placeholder="Begin typing to filter" id="filter" /> <input type="button" id="toggle-completed" value="Hide completed" /> <input type="button" id="toggle-active" value="Hide active" /> <input type="button" id="clear-filter" value="Clear filters" /> </div> <% paginated(@experiments).each do |experiment| %> <% if experiment.goals.empty? %> <%= erb :_experiment, :locals => {:goal => nil, :experiment => experiment} %> <% else %> <%= erb :_experiment_with_goal_header, :locals => {:experiment => experiment} %> <% experiment.goals.each do |g| %> <%= erb :_experiment, :locals => {:goal => g, :experiment => experiment} %> <% end %> <% end %> <% end %> <td><%= alternative.participant_count %></td> <td><%= alternative.participant_count - alternative.completed_count %></td> <td><%= alternative.completed_count %></td> <td><%= (alternative.conversion_rate * 100).round(2) %>%</td> <td><%= alternative.z_score %></td> <td> <% if experiment.winner %> <% end %> <div class="dashboard-controls dashboard-controls-bottom"> <form action="<%= url "/initialize_experiment" %>" method='post'> <label>Add unregistered experiment: </label> <select name="experiment" id="experiment-select"> <option selected disabled>experiment</option> <% @unintialized_experiments.sort.each do |experiment_name| %> <option value="<%= experiment_name %>"><%= experiment_name %></option> <% end %> </select> <input type="submit" id="register-experiment-btn" value="register experiment"/> </form> <div> <MSG> More robust conversion rate <DFF> @@ -21,7 +21,7 @@ <td><%= alternative.participant_count %></td> <td><%= alternative.participant_count - alternative.completed_count %></td> <td><%= alternative.completed_count %></td> - <td><%= (alternative.conversion_rate * 100).round(2) %>%</td> + <td><%= number_to_percentage(alternative.conversion_rate) %>%</td> <td><%= alternative.z_score %></td> <td> <% if experiment.winner %>
1
More robust conversion rate
1
.erb
erb
mit
splitrb/split
10072146
<NME> index.erb <BEF> <% if @experiments.any? %> <p class="intro">The list below contains all the registered experiments along with the number of test participants, completed and conversion rate currently in the system.</p> <div class="dashboard-controls"> <input type="text" placeholder="Begin typing to filter" id="filter" /> <input type="button" id="toggle-completed" value="Hide completed" /> <input type="button" id="toggle-active" value="Hide active" /> <input type="button" id="clear-filter" value="Clear filters" /> </div> <% paginated(@experiments).each do |experiment| %> <% if experiment.goals.empty? %> <%= erb :_experiment, :locals => {:goal => nil, :experiment => experiment} %> <% else %> <%= erb :_experiment_with_goal_header, :locals => {:experiment => experiment} %> <% experiment.goals.each do |g| %> <%= erb :_experiment, :locals => {:goal => g, :experiment => experiment} %> <% end %> <% end %> <% end %> <td><%= alternative.participant_count %></td> <td><%= alternative.participant_count - alternative.completed_count %></td> <td><%= alternative.completed_count %></td> <td><%= (alternative.conversion_rate * 100).round(2) %>%</td> <td><%= alternative.z_score %></td> <td> <% if experiment.winner %> <% end %> <div class="dashboard-controls dashboard-controls-bottom"> <form action="<%= url "/initialize_experiment" %>" method='post'> <label>Add unregistered experiment: </label> <select name="experiment" id="experiment-select"> <option selected disabled>experiment</option> <% @unintialized_experiments.sort.each do |experiment_name| %> <option value="<%= experiment_name %>"><%= experiment_name %></option> <% end %> </select> <input type="submit" id="register-experiment-btn" value="register experiment"/> </form> <div> <MSG> More robust conversion rate <DFF> @@ -21,7 +21,7 @@ <td><%= alternative.participant_count %></td> <td><%= alternative.participant_count - alternative.completed_count %></td> <td><%= alternative.completed_count %></td> - <td><%= (alternative.conversion_rate * 100).round(2) %>%</td> + <td><%= number_to_percentage(alternative.conversion_rate) %>%</td> <td><%= alternative.z_score %></td> <td> <% if experiment.winner %>
1
More robust conversion rate
1
.erb
erb
mit
splitrb/split
10072147
<NME> index.erb <BEF> <% if @experiments.any? %> <p class="intro">The list below contains all the registered experiments along with the number of test participants, completed and conversion rate currently in the system.</p> <div class="dashboard-controls"> <input type="text" placeholder="Begin typing to filter" id="filter" /> <input type="button" id="toggle-completed" value="Hide completed" /> <input type="button" id="toggle-active" value="Hide active" /> <input type="button" id="clear-filter" value="Clear filters" /> </div> <% paginated(@experiments).each do |experiment| %> <% if experiment.goals.empty? %> <%= erb :_experiment, :locals => {:goal => nil, :experiment => experiment} %> <% else %> <%= erb :_experiment_with_goal_header, :locals => {:experiment => experiment} %> <% experiment.goals.each do |g| %> <%= erb :_experiment, :locals => {:goal => g, :experiment => experiment} %> <% end %> <% end %> <% end %> <td><%= alternative.participant_count %></td> <td><%= alternative.participant_count - alternative.completed_count %></td> <td><%= alternative.completed_count %></td> <td><%= (alternative.conversion_rate * 100).round(2) %>%</td> <td><%= alternative.z_score %></td> <td> <% if experiment.winner %> <% end %> <div class="dashboard-controls dashboard-controls-bottom"> <form action="<%= url "/initialize_experiment" %>" method='post'> <label>Add unregistered experiment: </label> <select name="experiment" id="experiment-select"> <option selected disabled>experiment</option> <% @unintialized_experiments.sort.each do |experiment_name| %> <option value="<%= experiment_name %>"><%= experiment_name %></option> <% end %> </select> <input type="submit" id="register-experiment-btn" value="register experiment"/> </form> <div> <MSG> More robust conversion rate <DFF> @@ -21,7 +21,7 @@ <td><%= alternative.participant_count %></td> <td><%= alternative.participant_count - alternative.completed_count %></td> <td><%= alternative.completed_count %></td> - <td><%= (alternative.conversion_rate * 100).round(2) %>%</td> + <td><%= number_to_percentage(alternative.conversion_rate) %>%</td> <td><%= alternative.z_score %></td> <td> <% if experiment.winner %>
1
More robust conversion rate
1
.erb
erb
mit
splitrb/split
10072148
<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('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('a>((((b>c))))+d'), '<a><b><c></c></b><d></d></a>'); equal(parse('a>(((b>c))*4)+d'), '<a><b*4@0><c></c></b><b*4@1><c></c></b><b*4@2><c></c></b><b*4@3><c></c></b><d></d></a>'); equal(parse('(div>dl>(dt+dd)*2)'), '<div><dl><dt*2@0></dt><dd*2@0></dd><dt*2@1></dt><dd*2@1></dd></dl></div>'); equal(parse('a*2>b*3'), '<a*2@0><b*3@0></b><b*3@1></b><b*3@2></b></a><a*2@1><b*3@0></b><b*3@1></b><b*3@2></b></a>'); equal(parse('a>(b+c)*2'), '<a><b*2@0></b><c*2@0></c><b*2@1></b><c*2@1></c></a>'); equal(parse('a>(b+c)*2+(d+e)*2'), '<a><b*2@0></b><c*2@0></c><b*2@1></b><c*2@1></c><d*2@0></d><e*2@0></e><d*2@1></d><e*2@1></e></a>'); // Should move `<div>` as sibling of `{foo}` 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[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> Fix wrap around anchor elements with classes (#656) <DFF> @@ -21,6 +21,8 @@ describe('Convert token abbreviations', () => { 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>'); }); @@ -69,6 +71,10 @@ describe('Convert token abbreviations', () => { 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>');
6
Fix wrap around anchor elements with classes (#656)
0
.ts
ts
mit
emmetio/emmet
10072149
<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('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('a>((((b>c))))+d'), '<a><b><c></c></b><d></d></a>'); equal(parse('a>(((b>c))*4)+d'), '<a><b*4@0><c></c></b><b*4@1><c></c></b><b*4@2><c></c></b><b*4@3><c></c></b><d></d></a>'); equal(parse('(div>dl>(dt+dd)*2)'), '<div><dl><dt*2@0></dt><dd*2@0></dd><dt*2@1></dt><dd*2@1></dd></dl></div>'); equal(parse('a*2>b*3'), '<a*2@0><b*3@0></b><b*3@1></b><b*3@2></b></a><a*2@1><b*3@0></b><b*3@1></b><b*3@2></b></a>'); equal(parse('a>(b+c)*2'), '<a><b*2@0></b><c*2@0></c><b*2@1></b><c*2@1></c></a>'); equal(parse('a>(b+c)*2+(d+e)*2'), '<a><b*2@0></b><c*2@0></c><b*2@1></b><c*2@1></c><d*2@0></d><e*2@0></e><d*2@1></d><e*2@1></e></a>'); // Should move `<div>` as sibling of `{foo}` 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[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> Fix wrap around anchor elements with classes (#656) <DFF> @@ -21,6 +21,8 @@ describe('Convert token abbreviations', () => { 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>'); }); @@ -69,6 +71,10 @@ describe('Convert token abbreviations', () => { 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>');
6
Fix wrap around anchor elements with classes (#656)
0
.ts
ts
mit
emmetio/emmet