From c5e229b696be87cba0bba78b66fcb9631f9b0c62 Mon Sep 17 00:00:00 2001 From: John Nunemaker Date: Sat, 31 Jan 2009 00:50:10 -0500 Subject: [PATCH] Added multiple specs and fixed bug where snake_case was not defined for string. Hash, String and HTTParty::XML all got spec additions. --- lib/core_extensions.rb | 6 + spec/hash_spec.rb | 44 ++++ spec/httparty/xml_spec.rb | 445 ++++++++++++++++++++++++++++++++++++++ spec/string_spec.rb | 27 +++ 4 files changed, 522 insertions(+) create mode 100644 spec/hash_spec.rb create mode 100644 spec/httparty/xml_spec.rb create mode 100644 spec/string_spec.rb diff --git a/lib/core_extensions.rb b/lib/core_extensions.rb index 61b292c..abb725e 100644 --- a/lib/core_extensions.rb +++ b/lib/core_extensions.rb @@ -79,6 +79,12 @@ class String #:nodoc: def blank? strip.empty? end unless method_defined?(:blank?) + + def snake_case + return self.downcase if self =~ /^[A-Z]+$/ + self.gsub(/([A-Z]+)(?=[A-Z][a-z]?)|\B[A-Z]/, '_\&') =~ /_*(.*)/ + return $+.downcase + end unless method_defined?(:snake_case) end # class String class Hash #:nodoc: diff --git a/spec/hash_spec.rb b/spec/hash_spec.rb new file mode 100644 index 0000000..54079c9 --- /dev/null +++ b/spec/hash_spec.rb @@ -0,0 +1,44 @@ +require File.dirname(__FILE__) + '/spec_helper' + +describe Hash, "to_xml_attributes" do + before do + @hash = { :one => "ONE", "two" => "TWO" } + end + + it "should turn the hash into xml attributes" do + attrs = @hash.to_xml_attributes + attrs.should match(/one="ONE"/m) + attrs.should match(/two="TWO"/m) + end + + it 'should preserve _ in hash keys' do + attrs = { + :some_long_attribute => "with short value", + :crash => :burn, + :merb => "uses extlib" + }.to_xml_attributes + + attrs.should =~ /some_long_attribute="with short value"/ + attrs.should =~ /merb="uses extlib"/ + attrs.should =~ /crash="burn"/ + end +end + + +describe Hash, 'to_params' do + { + { "foo" => "bar", "baz" => "bat" } => "foo=bar&baz=bat", + { "foo" => [ "bar", "baz" ] } => "foo[]=bar&foo[]=baz", + { "foo" => [ {"bar" => "1"}, {"bar" => 2} ] } => "foo[][bar]=1&foo[][bar]=2", + { "foo" => { "bar" => [ {"baz" => 1}, {"baz" => "2"} ] } } => "foo[bar][][baz]=1&foo[bar][][baz]=2", + { "foo" => {"1" => "bar", "2" => "baz"} } => "foo[1]=bar&foo[2]=baz" + }.each do |hash, params| + it "should covert hash: #{hash.inspect} to params: #{params.inspect}" do + hash.to_params.split('&').sort.should == params.split('&').sort + end + end + + it 'should not leave a trailing &' do + { :name => 'Bob', :address => { :street => '111 Ruby Ave.', :city => 'Ruby Central', :phones => ['111-111-1111', '222-222-2222'] } }.to_params.should_not match(/&$/) + end +end \ No newline at end of file diff --git a/spec/httparty/xml_spec.rb b/spec/httparty/xml_spec.rb new file mode 100644 index 0000000..2a2cb4c --- /dev/null +++ b/spec/httparty/xml_spec.rb @@ -0,0 +1,445 @@ +require File.join(File.dirname(__FILE__), '..', 'spec_helper') + +require "date" +require 'bigdecimal' + +describe HTTParty::XML, "#parse" do + it "should transform a simple tag with content" do + xml = "This is the contents" + HTTParty::XML.parse(xml).should == { 'tag' => 'This is the contents' } + end + + it "should work with cdata tags" do + xml = <<-END + + + + END + HTTParty::XML.parse(xml)["tag"].strip.should == "text inside cdata" + end + + it "should transform a simple tag with attributes" do + xml = "" + hash = { 'tag' => { 'attr1' => '1', 'attr2' => '2' } } + HTTParty::XML.parse(xml).should == hash + end + + it "should transform repeating siblings into an array" do + xml =<<-XML + + + + + XML + + HTTParty::XML.parse(xml)['opt']['user'].should be_an_instance_of(Array) + + hash = { + 'opt' => { + 'user' => [{ + 'login' => 'grep', + 'fullname' => 'Gary R Epstein' + },{ + 'login' => 'stty', + 'fullname' => 'Simon T Tyson' + }] + } + } + + HTTParty::XML.parse(xml).should == hash + end + + it "should not transform non-repeating siblings into an array" do + xml =<<-XML + + + + XML + + HTTParty::XML.parse(xml)['opt']['user'].should be_an_instance_of(Hash) + + hash = { + 'opt' => { + 'user' => { + 'login' => 'grep', + 'fullname' => 'Gary R Epstein' + } + } + } + + HTTParty::XML.parse(xml).should == hash + end + + it "should typecast an integer" do + xml = "10" + HTTParty::XML.parse(xml)['tag'].should == 10 + end + + it "should typecast a true boolean" do + xml = "true" + HTTParty::XML.parse(xml)['tag'].should be_true + end + + it "should typecast a false boolean" do + ["false"].each do |w| + HTTParty::XML.parse("#{w}")['tag'].should be_false + end + end + + it "should typecast a datetime" do + xml = "2007-12-31 10:32" + HTTParty::XML.parse(xml)['tag'].should == Time.parse( '2007-12-31 10:32' ).utc + end + + it "should typecast a date" do + xml = "2007-12-31" + HTTParty::XML.parse(xml)['tag'].should == Date.parse('2007-12-31') + end + + it "should unescape html entities" do + values = { + "<" => "<", + ">" => ">", + '"' => """, + "'" => "'", + "&" => "&" + } + values.each do |k,v| + xml = "Some content #{v}" + HTTParty::XML.parse(xml)['tag'].should match(Regexp.new(k)) + end + end + + it "should undasherize keys as tags" do + xml = "Stuff" + HTTParty::XML.parse(xml).keys.should include( 'tag_1' ) + end + + it "should undasherize keys as attributes" do + xml = "" + HTTParty::XML.parse(xml)['tag1'].keys.should include( 'attr_1') + end + + it "should undasherize keys as tags and attributes" do + xml = "" + HTTParty::XML.parse(xml).keys.should include( 'tag_1' ) + HTTParty::XML.parse(xml)['tag_1'].keys.should include( 'attr_1') + end + + it "should render nested content correctly" do + xml = "Tag1 Content This is strong" + HTTParty::XML.parse(xml)['root']['tag1'].should == "Tag1 Content This is strong" + end + + it "should render nested content with split text nodes correctly" do + xml = "Tag1 ContentStuff Hi There" + HTTParty::XML.parse(xml)['root'].should == "Tag1 ContentStuff Hi There" + end + + it "should ignore attributes when a child is a text node" do + xml = "Stuff" + HTTParty::XML.parse(xml).should == { "root" => "Stuff" } + end + + it "should ignore attributes when any child is a text node" do + xml = "Stuff in italics" + HTTParty::XML.parse(xml).should == { "root" => "Stuff in italics" } + end + + it "should correctly transform multiple children" do + xml = <<-XML + + 35 + Home Simpson + 1988-01-01 + 2000-04-28 23:01 + true + + XML + + hash = { + "user" => { + "gender" => "m", + "age" => 35, + "name" => "Home Simpson", + "dob" => Date.parse('1988-01-01'), + "joined_at" => Time.parse("2000-04-28 23:01"), + "is_cool" => true + } + } + + HTTParty::XML.parse(xml).should == hash + end + + it "should properly handle nil values (ActiveSupport Compatible)" do + topic_xml = <<-EOT + + + + + + + + + + EOT + + expected_topic_hash = { + 'title' => nil, + 'id' => nil, + 'approved' => nil, + 'written_on' => nil, + 'viewed_at' => nil, + 'content' => nil, + 'parent_id' => nil + } + HTTParty::XML.parse(topic_xml)["topic"].should == expected_topic_hash + end + + it "should handle a single record from xml (ActiveSupport Compatible)" do + topic_xml = <<-EOT + + The First Topic + David + 1 + true + 0 + 2592000000 + 2003-07-16 + 2003-07-16T09:28:00+0000 + --- \n1: should be an integer\n:message: Have a nice day\narray: \n- should-have-dashes: true\n should_have_underscores: true\n + david@loudthinking.com + + 1.5 + 135 + yes + + EOT + + expected_topic_hash = { + 'title' => "The First Topic", + 'author_name' => "David", + 'id' => 1, + 'approved' => true, + 'replies_count' => 0, + 'replies_close_in' => 2592000000, + 'written_on' => Date.new(2003, 7, 16), + 'viewed_at' => Time.utc(2003, 7, 16, 9, 28), + # Changed this line where the key is :message. The yaml specifies this as a symbol, and who am I to change what you specify + # The line in ActiveSupport is + # 'content' => { 'message' => "Have a nice day", 1 => "should be an integer", "array" => [{ "should-have-dashes" => true, "should_have_underscores" => true }] }, + 'content' => { :message => "Have a nice day", 1 => "should be an integer", "array" => [{ "should-have-dashes" => true, "should_have_underscores" => true }] }, + 'author_email_address' => "david@loudthinking.com", + 'parent_id' => nil, + 'ad_revenue' => BigDecimal("1.50"), + 'optimum_viewing_angle' => 135.0, + 'resident' => :yes + } + + HTTParty::XML.parse(topic_xml)["topic"].each do |k,v| + v.should == expected_topic_hash[k] + end + end + + it "should handle multiple records (ActiveSupport Compatible)" do + topics_xml = <<-EOT + + + The First Topic + David + 1 + false + 0 + 2592000000 + 2003-07-16 + 2003-07-16T09:28:00+0000 + Have a nice day + david@loudthinking.com + + + + The Second Topic + Jason + 1 + false + 0 + 2592000000 + 2003-07-16 + 2003-07-16T09:28:00+0000 + Have a nice day + david@loudthinking.com + + + + EOT + + expected_topic_hash = { + 'title' => "The First Topic", + 'author_name' => "David", + 'id' => 1, + 'approved' => false, + 'replies_count' => 0, + 'replies_close_in' => 2592000000, + 'written_on' => Date.new(2003, 7, 16), + 'viewed_at' => Time.utc(2003, 7, 16, 9, 28), + 'content' => "Have a nice day", + 'author_email_address' => "david@loudthinking.com", + 'parent_id' => nil + } + # puts HTTParty::XML.parse(topics_xml)['topics'].first.inspect + HTTParty::XML.parse(topics_xml)["topics"].first.each do |k,v| + v.should == expected_topic_hash[k] + end + end + + it "should handle a single record from_xml with attributes other than type (ActiveSupport Compatible)" do + topic_xml = <<-EOT + + + + + + EOT + + expected_topic_hash = { + 'id' => "175756086", + 'owner' => "55569174@N00", + 'secret' => "0279bf37a1", + 'server' => "76", + 'title' => "Colored Pencil PhotoBooth Fun", + 'ispublic' => "1", + 'isfriend' => "0", + 'isfamily' => "0", + } + HTTParty::XML.parse(topic_xml)["rsp"]["photos"]["photo"].each do |k,v| + v.should == expected_topic_hash[k] + end + end + + it "should handle an emtpy array (ActiveSupport Compatible)" do + blog_xml = <<-XML + + + + XML + expected_blog_hash = {"blog" => {"posts" => []}} + HTTParty::XML.parse(blog_xml).should == expected_blog_hash + end + + it "should handle empty array with whitespace from xml (ActiveSupport Compatible)" do + blog_xml = <<-XML + + + + + XML + expected_blog_hash = {"blog" => {"posts" => []}} + HTTParty::XML.parse(blog_xml).should == expected_blog_hash + end + + it "should handle array with one entry from_xml (ActiveSupport Compatible)" do + blog_xml = <<-XML + + + a post + + + XML + expected_blog_hash = {"blog" => {"posts" => ["a post"]}} + HTTParty::XML.parse(blog_xml).should == expected_blog_hash + end + + it "should handle array with multiple entries from xml (ActiveSupport Compatible)" do + blog_xml = <<-XML + + + a post + another post + + + XML + expected_blog_hash = {"blog" => {"posts" => ["a post", "another post"]}} + HTTParty::XML.parse(blog_xml).should == expected_blog_hash + end + + it "should handle file types (ActiveSupport Compatible)" do + blog_xml = <<-XML + + + + + XML + hash = HTTParty::XML.parse(blog_xml) + hash.should have_key('blog') + hash['blog'].should have_key('logo') + + file = hash['blog']['logo'] + file.original_filename.should == 'logo.png' + file.content_type.should == 'image/png' + end + + it "should handle file from xml with defaults (ActiveSupport Compatible)" do + blog_xml = <<-XML + + + + + XML + file = HTTParty::XML.parse(blog_xml)['blog']['logo'] + file.original_filename.should == 'untitled' + file.content_type.should == 'application/octet-stream' + end + + it "should handle xsd like types from xml (ActiveSupport Compatible)" do + bacon_xml = <<-EOT + + 0.5 + 12.50 + 1 + 2007-12-25T12:34:56+0000 + + YmFiZS5wbmc= + + EOT + + expected_bacon_hash = { + 'weight' => 0.5, + 'chunky' => true, + 'price' => BigDecimal("12.50"), + 'expires_at' => Time.utc(2007,12,25,12,34,56), + 'notes' => "", + 'illustration' => "babe.png" + } + + HTTParty::XML.parse(bacon_xml)["bacon"].should == expected_bacon_hash + end + + it "should let type trickle through when unknown (ActiveSupport Compatible)" do + product_xml = <<-EOT + + 0.5 + image.gif + + + EOT + + expected_product_hash = { + 'weight' => 0.5, + 'image' => {'type' => 'ProductImage', 'filename' => 'image.gif' }, + } + + HTTParty::XML.parse(product_xml)["product"].should == expected_product_hash + end + + it "should handle unescaping from xml (ActiveResource Compatible)" do + xml_string = 'First & Last NameFirst &amp; Last Name' + expected_hash = { + 'bare_string' => 'First & Last Name', + 'pre_escaped_string' => 'First & Last Name' + } + + HTTParty::XML.parse(xml_string)['person'].should == expected_hash + end +end \ No newline at end of file diff --git a/spec/string_spec.rb b/spec/string_spec.rb new file mode 100644 index 0000000..54867a2 --- /dev/null +++ b/spec/string_spec.rb @@ -0,0 +1,27 @@ +describe String, "#snake_case" do + it "lowercases one word CamelCase" do + "Merb".snake_case.should == "merb" + end + + it "makes one underscore snake_case two word CamelCase" do + "MerbCore".snake_case.should == "merb_core" + end + + it "handles CamelCase with more than 2 words" do + "SoYouWantContributeToMerbCore".snake_case.should == "so_you_want_contribute_to_merb_core" + end + + it "handles CamelCase with more than 2 capital letter in a row" do + "CNN".snake_case.should == "cnn" + "CNNNews".snake_case.should == "cnn_news" + "HeadlineCNNNews".snake_case.should == "headline_cnn_news" + end + + it "does NOT change one word lowercase" do + "merb".snake_case.should == "merb" + end + + it "leaves snake_case as is" do + "merb_core".snake_case.should == "merb_core" + end +end \ No newline at end of file