From 4f845757f975e09f876965af2b190c245e76e0a5 Mon Sep 17 00:00:00 2001 From: Kanezoh Date: Fri, 6 Aug 2021 16:58:31 +0900 Subject: [PATCH] add cookie path attribute test --- spec/cookie_spec.cr | 16 ++++++++++++++++ src/mechanize/http/agent.cr | 10 ++++++++-- 2 files changed, 24 insertions(+), 2 deletions(-) diff --git a/spec/cookie_spec.cr b/spec/cookie_spec.cr index b5184ed..05973c0 100644 --- a/spec/cookie_spec.cr +++ b/spec/cookie_spec.cr @@ -4,6 +4,9 @@ WebMock.stub(:get, "example.com/cookies1").to_return(headers: {"Set-Cookie" => " WebMock.stub(:get, "example.com/cookies1_domain").to_return(headers: {"Set-Cookie" => "id=123; Domain=example.com"}) WebMock.stub(:get, "example.com/cookies2").to_return(headers: {"Set-Cookie" => "name=kanezoh"}) WebMock.stub(:get, "example.com/cookies3").to_return(headers: {"Set-Cookie" => "id=456"}) +WebMock.stub(:get, "example.com/paths").to_return(headers: {"Set-Cookie" => "id=123; Path=/paths"}) +WebMock.stub(:get, "example.com/paths/hoge").to_return() +WebMock.stub(:get, "example.com/hoge/paths").to_return() WebMock.stub(:get, "www.example.com").to_return() WebMock.stub(:get, "example.com/meta_cookie").to_return(body: <<-BODY @@ -74,4 +77,17 @@ describe "Mechanize Cookie test" do agent.get("http://www.example.com/") agent.request_headers.has_key?("Cookie").should eq true end + + it "doesn't send not-matched path if path attribute is set" do + agent = Mechanize.new + agent.get("http://example.com/paths") + agent.get("http://example.com/") + agent.request_headers.has_key?("Cookie").should eq false + agent.get("http://example.com/paths") + agent.request_headers.has_key?("Cookie").should eq true + agent.get("http://example.com/paths/hoge") + agent.request_headers.has_key?("Cookie").should eq true + agent.get("http://example.com/hoge/paths") + agent.request_headers.has_key?("Cookie").should eq false + end end diff --git a/src/mechanize/http/agent.cr b/src/mechanize/http/agent.cr index 110ca70..b2f421e 100644 --- a/src/mechanize/http/agent.cr +++ b/src/mechanize/http/agent.cr @@ -131,7 +131,7 @@ module MechanizeCr host = uri.host valid_cookies = ::HTTP::Cookies.new request_cookies.each do |cookie| - valid_cookies << cookie if cookie.valid_cookie?(host) + valid_cookies << cookie if cookie.valid_cookie?(uri) end valid_cookies end @@ -157,7 +157,13 @@ class HTTP::Cookie @origin = origin end - def valid_cookie?(host) + def valid_cookie?(uri) + host = uri.host + if path + bool = uri.path.try &.=~(/^#{path}.*/) + return false if bool.nil? + end + if domain host.try &.=~(/.*#{domain.try &.gsub(".", "\.")}$/) else