From f3bd9845e37b4c06989f6870d1c4fb3940faa3b6 Mon Sep 17 00:00:00 2001 From: Kanezoh Date: Sun, 13 Jun 2021 07:58:50 +0900 Subject: [PATCH] add cookie test --- spec/agent_spec.cr | 40 +++++++++++++++++++++++++++++-------- src/mechanize/http/agent.cr | 2 +- 2 files changed, 33 insertions(+), 9 deletions(-) diff --git a/spec/agent_spec.cr b/spec/agent_spec.cr index 907ed56..522eceb 100644 --- a/spec/agent_spec.cr +++ b/spec/agent_spec.cr @@ -1,4 +1,7 @@ require "./spec_helper" +WebMock.stub(:get, "example.com/") +WebMock.stub(:get, "example.com/cookies1").to_return(headers: {"Set-Cookie" => "id=123"}) +WebMock.stub(:get, "example.com/cookies2").to_return(headers: {"Set-Cookie" => "name=kanezoh"}) WebMock.stub(:get, "html_example.com").to_return(body: <<-BODY @@ -21,12 +24,33 @@ WebMock.stub(:post, "http://html_example.com/post_path"). to_return(body: "success") describe "Mechanize Agent test" do - agent = Mechanize.new - page = agent.get("http://html_example.com/") - form = page.forms[0] - form.field_with("name").value = "foo" - form.field_with("email").value = "bar" - page = agent.submit(form) - page.not_nil!.code.should eq 200 - page.not_nil!.body.should eq "success" + it "fill and submit form" do + agent = Mechanize.new + page = agent.get("http://html_example.com/") + form = page.forms[0] + form.field_with("name").value = "foo" + form.field_with("email").value = "bar" + page = agent.submit(form) + page.not_nil!.code.should eq 200 + page.not_nil!.body.should eq "success" + end + + it "receive and send cookie" do + agent = Mechanize.new + # receive cookies + agent.get("http://example.com/cookies1") + # send cookies + agent.get("http://example.com/") + agent.request_headers["Cookie"].should eq "id=123" + end + + it "receive and send multiple cookies" do + agent = Mechanize.new + # receive cookies1 + agent.get("http://example.com/cookies1") + # receive cookies2 + agent.get("http://example.com/cookies2") + agent.get("http://example.com/") + agent.request_headers["Cookie"].should eq "id=123; name=kanezoh" + end end diff --git a/src/mechanize/http/agent.cr b/src/mechanize/http/agent.cr index 40d0104..30c0f83 100644 --- a/src/mechanize/http/agent.cr +++ b/src/mechanize/http/agent.cr @@ -74,7 +74,7 @@ module MechanizeCr # end #end header_cookies = response.try &.cookies - if (header_cookies.nil?) + if (header_cookies.nil? || header_cookies.try &.empty?) request_headers else if cookies.fetch(uri.host.to_s, ::HTTP::Cookies.new).empty?