[DRE-commits] [ruby-recaptcha] 02/04: Imported Upstream version 0.4.0

David Martínez ender at moszumanska.debian.org
Tue Jul 28 08:00:23 UTC 2015


This is an automated email from the git hooks/post-receive script.

ender pushed a commit to branch master
in repository ruby-recaptcha.

commit 3d60c1a7bb892523237aa1022a8b4a1d1c444352
Author: David Martínez Moreno <ender at debian.org>
Date:   Mon Jul 27 23:19:41 2015 -0700

    Imported Upstream version 0.4.0
---
 .gitignore                           |  7 +++-
 .travis.yml                          |  3 ++
 CHANGELOG                            |  8 ++++
 Gemfile.lock                         | 52 ++++++++++++++++++++++++
 README.rdoc                          | 13 ++++--
 Rakefile                             |  5 +--
 lib/recaptcha.rb                     | 24 ++++++++++--
 lib/recaptcha/client_helper.rb       | 58 +++++++++++++++++++++++++--
 lib/recaptcha/configuration.rb       | 30 ++++++++++----
 lib/recaptcha/verify.rb              | 76 ++++++++++++++++++++++++++----------
 lib/recaptcha/version.rb             |  2 +-
 recaptcha.gemspec                    |  2 +
 test/recaptcha_configuration_test.rb | 44 +++++++++++++++++++++
 test/recaptcha_test.rb               | 38 +++++++-----------
 test/recaptcha_v1_test.rb            | 35 +++++++++++++++++
 test/verify_recaptcha_test.rb        | 56 ++++++++++++++++++++++----
 16 files changed, 379 insertions(+), 74 deletions(-)

diff --git a/.gitignore b/.gitignore
index 0c8ab5e..13d7fea 100644
--- a/.gitignore
+++ b/.gitignore
@@ -1,3 +1,8 @@
 rdoc
 pkg
-Gemfile.lock
+.ruby-gemset
+.ruby-version
+.bundle
+
+.gems
+.rbenv-gemsets
diff --git a/.travis.yml b/.travis.yml
new file mode 100644
index 0000000..8a8ac56
--- /dev/null
+++ b/.travis.yml
@@ -0,0 +1,3 @@
+language: ruby
+rvm:
+  - 2.1.2
diff --git a/CHANGELOG b/CHANGELOG
index 9e20eb9..6eb0df3 100644
--- a/CHANGELOG
+++ b/CHANGELOG
@@ -1,3 +1,11 @@
+== 0.3.6 / 2012-01-07
+
+* Many documentation changes
+* Fixed deprecations in dependencies
+* Protocol relative JS includes
+* Fixes for options hash
+* Fixes for failing tests
+
 == 0.3.5 / 2012-05-02
 
 * I18n for error messages
diff --git a/Gemfile.lock b/Gemfile.lock
new file mode 100644
index 0000000..6fd8ba1
--- /dev/null
+++ b/Gemfile.lock
@@ -0,0 +1,52 @@
+PATH
+  remote: .
+  specs:
+    recaptcha (0.4.0)
+
+GEM
+  remote: https://rubygems.org/
+  specs:
+    activesupport (4.1.8)
+      i18n (~> 0.6, >= 0.6.9)
+      json (~> 1.7, >= 1.7.7)
+      minitest (~> 5.1)
+      thread_safe (~> 0.1)
+      tzinfo (~> 1.1)
+    byebug (3.5.1)
+      columnize (~> 0.8)
+      debugger-linecache (~> 1.2)
+      slop (~> 3.6)
+    coderay (1.1.0)
+    columnize (0.8.9)
+    debugger-linecache (1.2.0)
+    i18n (0.6.11)
+    json (1.8.1)
+    metaclass (0.0.4)
+    method_source (0.8.2)
+    minitest (5.4.3)
+    mocha (1.1.0)
+      metaclass (~> 0.0.1)
+    pry (0.10.1)
+      coderay (~> 1.1.0)
+      method_source (~> 0.8.1)
+      slop (~> 3.4)
+    pry-byebug (2.0.0)
+      byebug (~> 3.4)
+      pry (~> 0.10)
+    rake (10.3.2)
+    slop (3.6.0)
+    thread_safe (0.3.4)
+    tzinfo (1.2.2)
+      thread_safe (~> 0.1)
+
+PLATFORMS
+  ruby
+
+DEPENDENCIES
+  activesupport
+  i18n
+  minitest (~> 5.0)
+  mocha
+  pry-byebug
+  rake
+  recaptcha!
diff --git a/README.rdoc b/README.rdoc
index fefb307..3887499 100644
--- a/README.rdoc
+++ b/README.rdoc
@@ -6,9 +6,10 @@ License::   {MIT}[http://creativecommons.org/licenses/MIT/]
 Info::      http://github.com/ambethia/recaptcha
 Bugs::      http://github.com/ambethia/recaptcha/issues
 
-This plugin adds helpers for the {reCAPTCHA API}[http://recaptcha.net]. In your
+This plugin adds helpers for the {reCAPTCHA API}[https://www.google.com/recaptcha]. In your
 views you can use the +recaptcha_tags+ method to embed the needed javascript,
-and you can validate in your controllers with +verify_recaptcha+.
+and you can validate in your controllers with +verify_recaptcha+ or +verify_recaptcha!+,
+which throws an error on failiure.
 
 Beforehand you need to configure Recaptcha with your custom private and public
 key. You may find detailed examples below. Exceptions will be raised if you
@@ -26,7 +27,7 @@ release and view it's README.
 == Setting up your API Keys
 
 There are multiple ways to setup your reCAPTCHA API key once you
-{obtain}[http://recaptcha.net/whyrecaptcha.html] a pair.
+{obtain}[https://www.google.com/recaptcha/admin] a pair.
 
 === Recaptcha.configure
 
@@ -36,7 +37,11 @@ into a +config/initializers/recaptcha.rb+ when used in a Rails project.
   Recaptcha.configure do |config|
     config.public_key  = '6Lc6BAAAAAAAAChqRbQZcn_yyyyyyyyyyyyyyyyy'
     config.private_key = '6Lc6BAAAAAAAAKN3DRm6VA_xxxxxxxxxxxxxxxxx'
-    config.proxy = 'http://myproxy.com.au:8080'
+    # Uncomment the following line if you are using a proxy server:
+    # config.proxy = 'http://myproxy.com.au:8080'
+    # Uncomment if you want to use the newer version of the API,
+    # only works for versions >= 0.3.7:
+    # config.api_version = 'v2'
   end
 
 This way, you may also set additional options to fit recaptcha into your
diff --git a/Rakefile b/Rakefile
index 93db262..cbedd72 100644
--- a/Rakefile
+++ b/Rakefile
@@ -1,9 +1,8 @@
 require "bundler/gem_tasks"
 require "rake/testtask"
 
-Rake::TestTask.new :test do |test|
-  test.libs << "lib"
-  test.pattern = "test/*_test.rb"
+Rake::TestTask.new do |t|
+  t.test_files = FileList['test/*_test.rb']
 end
 
 task :default => :test
diff --git a/lib/recaptcha.rb b/lib/recaptcha.rb
index d3f30d7..a260082 100644
--- a/lib/recaptcha.rb
+++ b/lib/recaptcha.rb
@@ -3,11 +3,23 @@ require 'recaptcha/client_helper'
 require 'recaptcha/verify'
 
 module Recaptcha
-  RECAPTCHA_API_SERVER_URL        = '//www.google.com/recaptcha/api'
-  RECAPTCHA_API_SECURE_SERVER_URL = 'https://www.google.com/recaptcha/api'
-  RECAPTCHA_VERIFY_URL            = 'http://www.google.com/recaptcha/api/verify'
-  USE_SSL_BY_DEFAULT              = false
+  CONFIG =
+    {
+      'v1' => {
+        'server_url' => '//www.google.com/recaptcha/api',
+        'secure_server_url' => 'https://www.google.com/recaptcha/api',
+        'verify_url' => 'http://www.google.com/recaptcha/api/verify'
+      },
+
+      'v2' => {
+        'server_url' => '//www.google.com/recaptcha/api.js',
+        'secure_server_url' => 'https://www.google.com/recaptcha/api.js',
+        'verify_url' => 'https://www.google.com/recaptcha/api/siteverify'
+      }
+    }
 
+  RECAPTCHA_API_VERSION           = 'v2' 
+  USE_SSL_BY_DEFAULT              = false
   HANDLE_TIMEOUTS_GRACEFULLY      = true
   SKIP_VERIFY_ENV = ['test', 'cucumber']
 
@@ -43,6 +55,10 @@ module Recaptcha
 
   class RecaptchaError < StandardError
   end
+
+  class VerifyError < RecaptchaError
+  end
+
 end
 
 if defined?(Rails)
diff --git a/lib/recaptcha/client_helper.rb b/lib/recaptcha/client_helper.rb
index f6e4038..7491fe2 100644
--- a/lib/recaptcha/client_helper.rb
+++ b/lib/recaptcha/client_helper.rb
@@ -3,6 +3,11 @@ module Recaptcha
     # Your public API can be specified in the +options+ hash or preferably
     # using the Configuration.
     def recaptcha_tags(options = {})
+      return v1_tags(options) if Recaptcha.configuration.v1?
+      return v2_tags(options) if Recaptcha.configuration.v2?
+    end # recaptcha_tags
+
+    def v1_tags(options)
       # Default options
       key   = options[:public_key] ||= Recaptcha.configuration.public_key
       raise RecaptchaError, "No public key specified." unless key
@@ -16,11 +21,18 @@ module Recaptcha
         html << %{</script>\n}
       end
       if options[:ajax]
+        if options[:display] && options[:display][:custom_theme_widget]
+          widget = options[:display][:custom_theme_widget]
+        else
+          widget = "dynamic_recaptcha"
+          html << <<-EOS
+           <div id="#{widget}"></div>
+          EOS
+        end
         html << <<-EOS
-          <div id="dynamic_recaptcha"></div>
           <script type="text/javascript">
             var rc_script_tag = document.createElement('script'),
-                rc_init_func = function(){Recaptcha.create("#{key}", document.getElementById("dynamic_recaptcha")#{',RecaptchaOptions' if options[:display]});}
+                rc_init_func = function(){Recaptcha.create("#{key}", document.getElementById("#{widget}")#{',RecaptchaOptions' if options[:display]});}
             rc_script_tag.src = "#{uri}/js/recaptcha_ajax.js";
             rc_script_tag.type = 'text/javascript';
             rc_script_tag.onload = function(){rc_init_func.call();};
@@ -48,7 +60,47 @@ module Recaptcha
         end
       end
       return (html.respond_to?(:html_safe) && html.html_safe) || html
-    end # recaptcha_tags
+    end
+
+    def v2_tags(options)
+      key   = options[:public_key] ||= Recaptcha.configuration.public_key
+      raise RecaptchaError, "No public key specified." unless key
+      error = options[:error] ||= ((defined? flash) ? flash[:recaptcha_error] : "")
+      uri   = Recaptcha.configuration.api_server_url(options[:ssl])
+      uri += "?hl=#{options[:hl]}" unless options[:hl].blank?
+      
+      v2_options = options.slice(:theme, :type, :callback).map {|k,v| %{data-#{k}="#{v}"} }.join(" ")
+
+      html = ""
+      html << %{<script src="#{uri}" async defer></script>\n}
+      html << %{<div class="g-recaptcha" data-sitekey="#{key}" #{v2_options}></div>\n}
+    
+      unless options[:noscript] == false
+        fallback_uri = "#{uri.chomp('.js')}/fallback?k=#{key}"
+        html << %{<noscript>}
+        html << %{<div style="width: 302px; height: 352px;">}
+        html << %{  <div style="width: 302px; height: 352px; position: relative;">}
+        html << %{    <div style="width: 302px; height: 352px; position: absolute;">}
+        html << %{      <iframe src="#{fallback_uri}"}
+        html << %{                frameborder="0" scrolling="no"}
+        html << %{                style="width: 302px; height:352px; border-style: none;">}
+        html << %{        </iframe>}
+        html << %{      </div>}
+        html << %{      <div style="width: 250px; height: 80px; position: absolute; border-style: none; }
+        html << %{             bottom: 21px; left: 25px; margin: 0px; padding: 0px; right: 25px;">}
+        html << %{        <textarea id="g-recaptcha-response" name="g-recaptcha-response" }
+        html << %{                  class="g-recaptcha-response" }
+        html << %{                  style="width: 250px; height: 80px; border: 1px solid #c1c1c1; }
+        html << %{                  margin: 0px; padding: 0px; resize: none;" value=""> }
+        html << %{        </textarea>}
+        html << %{      </div>}
+        html << %{    </div>}
+        html << %{  </div>}
+        html << %{</noscript>}
+      end
+
+      return (html.respond_to?(:html_safe) && html.html_safe) || html
+    end
 
     private
 
diff --git a/lib/recaptcha/configuration.rb b/lib/recaptcha/configuration.rb
index 6c76ef7..5dff06d 100644
--- a/lib/recaptcha/configuration.rb
+++ b/lib/recaptcha/configuration.rb
@@ -28,9 +28,7 @@ module Recaptcha
   #   end
   #
   class Configuration
-    attr_accessor :nonssl_api_server_url,
-                  :ssl_api_server_url,
-                  :verify_url,
+    attr_accessor :api_version, 
                   :skip_verify_env,
                   :private_key,
                   :public_key,
@@ -39,20 +37,38 @@ module Recaptcha
                   :use_ssl_by_default
 
     def initialize #:nodoc:
-      @nonssl_api_server_url      = RECAPTCHA_API_SERVER_URL
-      @ssl_api_server_url         = RECAPTCHA_API_SECURE_SERVER_URL
-      @verify_url                 = RECAPTCHA_VERIFY_URL
+      @api_version                = RECAPTCHA_API_VERSION
       @skip_verify_env            = SKIP_VERIFY_ENV
       @handle_timeouts_gracefully = HANDLE_TIMEOUTS_GRACEFULLY
       @use_ssl_by_default         = USE_SSL_BY_DEFAULT
 
       @private_key           = ENV['RECAPTCHA_PRIVATE_KEY']
-      @public_key            = ENV['RECAPTCHA_PUBLIC_KEY']
+      @public_key            = ENV['RECAPTCHA_PUBLIC_KEY']      
     end
 
     def api_server_url(ssl = nil) #:nodoc:
       ssl = use_ssl_by_default if ssl.nil?
       ssl ? ssl_api_server_url : nonssl_api_server_url
     end
+
+    def nonssl_api_server_url
+      CONFIG[@api_version]['server_url']
+    end
+
+    def ssl_api_server_url
+      CONFIG[@api_version]['secure_server_url']
+    end
+
+    def verify_url
+      CONFIG[@api_version]['verify_url']
+    end
+
+    def v1?
+      @api_version == 'v1'
+    end
+
+    def v2?
+      @api_version == 'v2'
+    end
   end
 end
diff --git a/lib/recaptcha/verify.rb b/lib/recaptcha/verify.rb
index 203b760..b398aab 100644
--- a/lib/recaptcha/verify.rb
+++ b/lib/recaptcha/verify.rb
@@ -4,12 +4,10 @@ module Recaptcha
     # Your private API can be specified in the +options+ hash or preferably
     # using the Configuration.
     def verify_recaptcha(options = {})
-      if !options.is_a? Hash
-        options = {:model => options}
-      end
+      options = {:model => options} unless options.is_a? Hash
 
-      env = options[:env] || ENV['RAILS_ENV']
-      return true if Recaptcha.configuration.skip_verify_env.include? env
+      env_options = options[:env] || ENV['RAILS_ENV']
+      return true if Recaptcha.configuration.skip_verify_env.include? env_options
       model = options[:model]
       attribute = options[:attribute] || :base
       private_key = options[:private_key] || Recaptcha.configuration.private_key
@@ -24,20 +22,49 @@ module Recaptcha
           http = Net::HTTP
         end
 
-        Timeout::timeout(options[:timeout] || 3) do
-          recaptcha = http.post_form(URI.parse(Recaptcha.configuration.verify_url), {
+        # env['REMOTE_ADDR'] to retrieve IP for Grape API
+        remote_ip = (request.respond_to?(:remote_ip) && request.remote_ip) || (env && env['REMOTE_ADDR'])
+        if Recaptcha.configuration.v1?
+          verify_hash = {
             "privatekey" => private_key,
-            "remoteip"   => request.remote_ip,
+            "remoteip"   => remote_ip,
             "challenge"  => params[:recaptcha_challenge_field],
             "response"   => params[:recaptcha_response_field]
-          })
+          }
+          Timeout::timeout(options[:timeout] || 3) do
+            recaptcha = http.post_form(URI.parse(Recaptcha.configuration.verify_url), verify_hash)
+          end
+          answer, error = recaptcha.body.split.map { |s| s.chomp }
+        end
+
+        if Recaptcha.configuration.v2?
+          verify_hash = {
+            "secret"    => private_key,
+            "remoteip"  => remote_ip,
+            "response"  => params['g-recaptcha-response']
+          }
+
+          Timeout::timeout(options[:timeout] || 3) do
+            uri = URI.parse(Recaptcha.configuration.verify_url + '?' + verify_hash.to_query)
+            http_instance = http.new(uri.host, uri.port)
+            if uri.port==443
+              http_instance.use_ssl =
+              http_instance.verify_mode = OpenSSL::SSL::VERIFY_NONE
+            end
+            request = Net::HTTP::Get.new(uri.request_uri)
+            recaptcha = http_instance.request(request)
+          end
+          answer, error = JSON.parse(recaptcha.body).values
         end
-        answer, error = recaptcha.body.split.map { |s| s.chomp }
-        unless answer == 'true'
-          flash[:recaptcha_error] = if defined?(I18n)
-            I18n.translate("recaptcha.errors.#{error}", {:default => error})
-          else
-            error
+
+        unless answer.to_s == 'true'
+          error = 'verification_failed' if error && Recaptcha.configuration.v2?
+          if request_in_html_format?
+            flash[:recaptcha_error] = if defined?(I18n)
+                                        I18n.translate("recaptcha.errors.#{error}", {:default => error})
+                                      else
+                                        error
+                                      end
           end
 
           if model
@@ -47,15 +74,17 @@ module Recaptcha
           end
           return false
         else
-          flash.delete(:recaptcha_error)
+          flash.delete(:recaptcha_error) if request_in_html_format?
           return true
         end
       rescue Timeout::Error
         if Recaptcha.configuration.handle_timeouts_gracefully
-          flash[:recaptcha_error] = if defined?(I18n)
-            I18n.translate('recaptcha.errors.recaptcha_unreachable', {:default => 'Recaptcha unreachable.'})
-          else
-            'Recaptcha unreachable.'
+          if request_in_html_format?
+            flash[:recaptcha_error] = if defined?(I18n)
+                                        I18n.translate('recaptcha.errors.recaptcha_unreachable', {:default => 'Recaptcha unreachable.'})
+                                      else
+                                        'Recaptcha unreachable.'
+                                      end
           end
 
           if model
@@ -71,5 +100,12 @@ module Recaptcha
         raise RecaptchaError, e.message, e.backtrace
       end
     end # verify_recaptcha
+
+    def request_in_html_format?
+      request.respond_to?(:format) && request.format == :html && respond_to?(:flash)
+    end
+    def verify_recaptcha!(options = {})
+      verify_recaptcha(options) or raise VerifyError
+    end #verify_recaptcha!
   end # Verify
 end # Recaptcha
diff --git a/lib/recaptcha/version.rb b/lib/recaptcha/version.rb
index 0fa6af6..a0e3e5b 100644
--- a/lib/recaptcha/version.rb
+++ b/lib/recaptcha/version.rb
@@ -1,3 +1,3 @@
 module Recaptcha
-  VERSION = "0.3.6"
+  VERSION = "0.4.0"
 end
diff --git a/recaptcha.gemspec b/recaptcha.gemspec
index 6e47baf..bfd8d02 100644
--- a/recaptcha.gemspec
+++ b/recaptcha.gemspec
@@ -21,4 +21,6 @@ Gem::Specification.new do |s|
   s.add_development_dependency "rake"
   s.add_development_dependency "activesupport"
   s.add_development_dependency "i18n"
+  s.add_development_dependency "minitest", "~> 5.0"
+  s.add_development_dependency "pry-byebug"
 end
diff --git a/test/recaptcha_configuration_test.rb b/test/recaptcha_configuration_test.rb
new file mode 100644
index 0000000..82467c8
--- /dev/null
+++ b/test/recaptcha_configuration_test.rb
@@ -0,0 +1,44 @@
+require 'minitest/autorun'
+require 'cgi'
+require File.dirname(File.expand_path(__FILE__)) + '/../lib/recaptcha'
+
+class RecaptchaConfigurationTest < Minitest::Test
+  include Recaptcha
+  include Recaptcha::ClientHelper
+  include Recaptcha::Verify
+
+  attr_accessor :session
+
+  def setup
+    @session = {}
+    @nonssl_api_server_url = Regexp.new(Regexp.quote(Recaptcha.configuration.nonssl_api_server_url) + '(.*)')
+    @ssl_api_server_url = Regexp.new(Regexp.quote(Recaptcha.configuration.ssl_api_server_url) + '(.*)')
+    Recaptcha.configure do |config|
+      config.public_key = '0000000000000000000000000000000000000000'
+      config.private_key = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
+      config.api_version = 'v2'
+    end
+  end
+
+  def test_recaptcha_api_version_default
+    assert_equal(Recaptcha.configuration.api_version, Recaptcha::RECAPTCHA_API_VERSION)
+  end
+
+  def test_v2_with_v2_api?
+    assert Recaptcha.configuration.v2?
+    refute Recaptcha.configuration.v1?
+  end
+
+  def test_different_configuration_within_with_configuration_block
+    key = Recaptcha.with_configuration(:public_key => '12345') do
+      Recaptcha.configuration.public_key
+    end
+
+    assert_equal('12345', key)
+  end
+
+  def test_reset_configuration_after_with_configuration_block
+    Recaptcha.with_configuration(:public_key => '12345')
+    assert_equal('0000000000000000000000000000000000000000', Recaptcha.configuration.public_key)
+  end
+end
\ No newline at end of file
diff --git a/test/recaptcha_test.rb b/test/recaptcha_test.rb
index 052e5da..68282bf 100644
--- a/test/recaptcha_test.rb
+++ b/test/recaptcha_test.rb
@@ -1,8 +1,8 @@
-require 'test/unit'
+require 'minitest/autorun'
 require 'cgi'
 require File.dirname(File.expand_path(__FILE__)) + '/../lib/recaptcha'
 
-class RecaptchaClientHelperTest < Test::Unit::TestCase
+class RecaptchaClientHelperTest < Minitest::Test
   include Recaptcha
   include Recaptcha::ClientHelper
   include Recaptcha::Verify
@@ -11,52 +11,44 @@ class RecaptchaClientHelperTest < Test::Unit::TestCase
 
   def setup
     @session = {}
+    @nonssl_api_server_url = Regexp.new(Regexp.quote(Recaptcha.configuration.nonssl_api_server_url) + '(.*)')
+    @ssl_api_server_url = Regexp.new(Regexp.quote(Recaptcha.configuration.ssl_api_server_url) + '(.*)')
     Recaptcha.configure do |config|
       config.public_key = '0000000000000000000000000000000000000000'
       config.private_key = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
     end
   end
 
-  def test_recaptcha_tags
-    # Might as well match something...
-    assert_match /"\/\/www.google.com\/recaptcha\/api\/challenge/, recaptcha_tags
+  def test_recaptcha_tags_v2
+    Recaptcha.configuration.api_version = 'v2'
+    # match a v2 only tag
+    assert_match /data-sitekey/, recaptcha_tags
+    # refute a v1 only tag
+    refute_match /\/challenge\?/, recaptcha_tags
   end
 
   def test_ssl_by_default
     Recaptcha.configuration.use_ssl_by_default = true
-    assert_match /https:\/\/www.google.com\/recaptcha\/api\/challenge/, recaptcha_tags
+    assert_match @ssl_api_server_url, recaptcha_tags
   end
 
   def test_relative_protocol_by_default_without_ssl
     Recaptcha.configuration.use_ssl_by_default = false
-    assert_match /\/\/www.google.com\/recaptcha\/api\/challenge/, recaptcha_tags(:ssl => false)
+    assert_match @nonssl_api_server_url, recaptcha_tags(:ssl => false)
   end
 
   def test_recaptcha_tags_with_ssl
-    assert_match /https:\/\/www.google.com\/recaptcha\/api\/challenge/, recaptcha_tags(:ssl => true)
+    assert_match @ssl_api_server_url, recaptcha_tags(:ssl => true)
   end
 
   def test_recaptcha_tags_without_noscript
-    assert_no_match /noscript/, recaptcha_tags(:noscript => false)
+    refute_match /noscript/, recaptcha_tags(:noscript => false)
   end
 
   def test_should_raise_exception_without_public_key
-    assert_raise RecaptchaError do
+    assert_raises RecaptchaError do
       Recaptcha.configuration.public_key = nil
       recaptcha_tags
     end
   end
-
-  def test_different_configuration_within_with_configuration_block
-    key = Recaptcha.with_configuration(:public_key => '12345') do
-      Recaptcha.configuration.public_key
-    end
-
-    assert_equal('12345', key)
-  end
-
-  def test_reset_configuration_after_with_configuration_block
-    Recaptcha.with_configuration(:public_key => '12345')
-    assert_equal('0000000000000000000000000000000000000000', Recaptcha.configuration.public_key)
-  end
 end
diff --git a/test/recaptcha_v1_test.rb b/test/recaptcha_v1_test.rb
new file mode 100644
index 0000000..df64474
--- /dev/null
+++ b/test/recaptcha_v1_test.rb
@@ -0,0 +1,35 @@
+require 'minitest/autorun'
+require 'cgi'
+require File.dirname(File.expand_path(__FILE__)) + '/../lib/recaptcha'
+
+class RecaptchaV1Test < Minitest::Test
+  include Recaptcha
+  include Recaptcha::ClientHelper
+  include Recaptcha::Verify
+
+  attr_accessor :session
+
+  def setup
+    @session = {}
+    @nonssl_api_server_url = Regexp.new(Regexp.quote(Recaptcha.configuration.nonssl_api_server_url) + '(.*)')
+    @ssl_api_server_url = Regexp.new(Regexp.quote(Recaptcha.configuration.ssl_api_server_url) + '(.*)')
+    Recaptcha.configure do |config|
+      config.public_key = '0000000000000000000000000000000000000000'
+      config.private_key = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
+      config.api_version = 'v1'
+    end
+  end
+
+  def test_v1_with_v1_api?
+    assert Recaptcha.configuration.v1?
+    refute Recaptcha.configuration.v2?
+  end
+
+  def test_recaptcah_tags_v1
+    Recaptcha.configuration.api_version = 'v1'
+    # match a v1 only tag
+    assert_match /\/challenge\?/, recaptcha_tags
+    # refute a v2 only tag
+    refute_match /data-sitekey/, recaptcha_tags
+  end
+end
\ No newline at end of file
diff --git a/test/verify_recaptcha_test.rb b/test/verify_recaptcha_test.rb
index afe1906..6c95dc2 100644
--- a/test/verify_recaptcha_test.rb
+++ b/test/verify_recaptcha_test.rb
@@ -1,6 +1,6 @@
 # coding: utf-8
 
-require 'test/unit'
+require 'minitest/autorun'
 require 'rubygems'
 require 'active_support'
 require 'active_support/core_ext/string'
@@ -9,30 +9,54 @@ require 'i18n'
 require 'net/http'
 require File.dirname(File.expand_path(__FILE__)) + '/../lib/recaptcha'
 
-class RecaptchaVerifyTest < Test::Unit::TestCase
+class RecaptchaVerifyTest < Minitest::Test
   def setup
     Recaptcha.configuration.private_key = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
     @controller = TestController.new
-    @controller.request = stub(:remote_ip => "1.1.1.1")
-    @controller.params = {:recaptcha_challenge_field => "challenge", :recaptcha_response_field => "response"}
+    @controller.request = stub(:remote_ip => "1.1.1.1", format: :html)
 
     @expected_post_data = {}
-    @expected_post_data["privatekey"] = Recaptcha.configuration.private_key
     @expected_post_data["remoteip"]   = @controller.request.remote_ip
-    @expected_post_data["challenge"]  = "challenge"
     @expected_post_data["response"]   = "response"
 
+    if Recaptcha.configuration.v1?
+      @controller.params = {:recaptcha_challenge_field => "challenge", :recaptcha_response_field => "response"}
+      @expected_post_data["privatekey"] = Recaptcha.configuration.private_key
+      @expected_post_data["challenge"]  = "challenge"
+    end
+
+    if Recaptcha.configuration.v2?
+      @controller.params = {:recaptcha_response_field => "response"}
+      @expected_post_data["secret"] = Recaptcha.configuration.private_key
+    end
+
     @expected_uri = URI.parse(Recaptcha.configuration.verify_url)
   end
 
+  def test_should_raise_exception_when_calling_bang_method
+    @controller.expects(:verify_recaptcha).returns(false)
+
+    assert_raises Recaptcha::VerifyError do
+      @controller.verify_recaptcha!
+    end
+  end
+
+  def test_should_return_whatever_verify_method_returns_when_using_bang_method
+    @controller.expects(:verify_recaptcha).returns(:foo)
+
+    assert_equal :foo, @controller.verify_recaptcha!
+  end
+
   def test_should_raise_exception_without_private_key
-    assert_raise Recaptcha::RecaptchaError do
+    skip
+    assert_raises Recaptcha::RecaptchaError do
       Recaptcha.configuration.private_key = nil
       @controller.verify_recaptcha
     end
   end
 
   def test_should_return_false_when_key_is_invalid
+    skip
     expect_http_post(response_with_body("false\ninvalid-site-private-key"))
 
     assert !@controller.verify_recaptcha
@@ -40,6 +64,7 @@ class RecaptchaVerifyTest < Test::Unit::TestCase
   end
 
   def test_returns_true_on_success
+    skip
     @controller.flash[:recaptcha_error] = "previous error that should be cleared"
     expect_http_post(response_with_body("true\n"))
 
@@ -48,6 +73,7 @@ class RecaptchaVerifyTest < Test::Unit::TestCase
   end
 
   def test_errors_should_be_added_to_model
+    skip
     expect_http_post(response_with_body("false\nbad-news"))
 
     errors = mock
@@ -59,6 +85,7 @@ class RecaptchaVerifyTest < Test::Unit::TestCase
   end
 
   def test_returns_true_on_success_with_optional_key
+    skip
     @controller.flash[:recaptcha_error] = "previous error that should be cleared"
     # reset private key
     @expected_post_data["privatekey"] =  'ADIFFERENTPRIVATEKEYXXXXXXXXXXXXXX'
@@ -69,15 +96,17 @@ class RecaptchaVerifyTest < Test::Unit::TestCase
   end
 
   def test_timeout
+    skip
     expect_http_post(Timeout::Error, :exception => true)
     assert !@controller.verify_recaptcha()
     assert_equal "Recaptcha unreachable.", @controller.flash[:recaptcha_error]
   end
 
   def test_timeout_when_handle_timeouts_gracefully_disabled
+    skip
     Recaptcha.with_configuration(:handle_timeouts_gracefully => false) do
       expect_http_post(Timeout::Error, :exception => true)
-      assert_raise Recaptcha::RecaptchaError, "Recaptcha unreachable." do
+      assert_raises Recaptcha::RecaptchaError, "Recaptcha unreachable." do
         assert @controller.verify_recaptcha()
       end
       assert_nil @controller.flash[:recaptcha_error]
@@ -85,6 +114,7 @@ class RecaptchaVerifyTest < Test::Unit::TestCase
   end
 
   def test_message_should_use_i18n
+    skip
     I18n.locale = :de
     verification_failed_translated   = "Sicherheitscode konnte nicht verifiziert werden."
     verification_failed_default      = "Word verification response is incorrect, please try again."
@@ -111,6 +141,7 @@ class RecaptchaVerifyTest < Test::Unit::TestCase
   end
 
   def test_it_translates_api_response_with_i18n
+    skip
     api_error_translated = "Bad news, body :("
     expect_http_post(response_with_body("false\nbad-news"))
     I18n.expects(:translate).with('recaptcha.errors.bad-news', :default => 'bad-news').returns(api_error_translated)
@@ -120,12 +151,21 @@ class RecaptchaVerifyTest < Test::Unit::TestCase
   end
 
   def test_it_fallback_to_api_response_if_i18n_translation_is_missing
+    skip
     expect_http_post(response_with_body("false\nbad-news"))
 
     assert !@controller.verify_recaptcha
     assert_equal 'bad-news', @controller.flash[:recaptcha_error]
   end
 
+  def test_not_flashing_error_if_request_format_not_in_html
+    skip
+    @controller.request = stub(:remote_ip => "1.1.1.1", format: :json)
+    expect_http_post(response_with_body("false\nbad-news"))
+    assert !@controller.verify_recaptcha
+    assert_nil @controller.flash[:recaptcha_error]
+  end
+
   private
 
   class TestController

-- 
Alioth's /usr/local/bin/git-commit-notice on /srv/git.debian.org/git/pkg-ruby-extras/ruby-recaptcha.git



More information about the Pkg-ruby-extras-commits mailing list