require 'ostruct' require 'test/unit' require File.join(File.dirname(__FILE__),"..","lib","refcode.rb") class RefcodeEncodableTest < Test::Unit::TestCase SECRET = "a short tidy secret, but not too short!" CODE_CONTENT = {:channel => 'email', :action => 'forward', :user_id => 14325, :unique_hash => 'f'} class BareEncodableObject < OpenStruct include Refcode::Encodable end class EncodableObjectSaltSymbol < BareEncodableObject has_refcode :secret => SECRET, :salt => :user_id end class EncodableObjectSaltString < BareEncodableObject has_refcode :secret => SECRET, :salt => "123 abc xyz" end class EncodableObjectSaltLambda < BareEncodableObject has_refcode :secret => SECRET, :salt => lambda { |me| "#{me.user_id}-42" } end class EncodableObjectSecretSymbol < BareEncodableObject has_refcode :secret => :unique_hash, :salt => :user_id end class EncodableObjectSecretString < BareEncodableObject has_refcode :secret => SECRET, :salt => "123 abc xyz" end class EncodableObjectSecretLambda < BareEncodableObject has_refcode :secret => lambda { |me| me.channel*20 }, :salt => "aaa" end def test_should_raise_argument_error_if_generate_refcode_called_without_val assert_raise ArgumentError do obj = EncodableObjectSaltString.new CODE_CONTENT obj.generate_refcode end end def test_should_raise_error_if_refcode_methods_called_before_has_refcode [:generate_refcode, :parse_refcode].each do |m| assert_raise Refcode::RefcodeInitException do obj = BareEncodableObject.new :some => 'value' obj.send m, "bogus value" end end end def test_should_raise_argument_error_if_has_refcode_called_without_correct_options assert_raise ArgumentError do obj = BareEncodableObject.new :some => 'value' obj.class.has_refcode :whatever => 'wrong' end end def test_should_raise_an_error_if_salt_is_empty obj = EncodableObjectSaltSymbol.new CODE_CONTENT obj.user_id = nil assert_raise RuntimeError do code = obj.generate_refcode CODE_CONTENT assert_equal CODE_CONTENT, obj.parse_refcode(code) end end def test_should_work_with_different_salt_options with_all_fixtures do |klass| obj = klass.new CODE_CONTENT code = obj.generate_refcode CODE_CONTENT assert_equal CODE_CONTENT, obj.parse_refcode(code) end end def test_should_work_with_different_secret_options with_all_fixtures do |klass| obj = klass.new CODE_CONTENT code = obj.generate_refcode CODE_CONTENT assert_equal CODE_CONTENT, obj.parse_refcode(code) end end def test_should_adjust_key_length_to_satisfy_encryption_algorithm content = CODE_CONTENT content[:unique_hash] = "x" obj = EncodableObjectSecretSymbol.new content code = obj.generate_refcode content assert_equal content, obj.parse_refcode(code) end private def with_all_fixtures [ EncodableObjectSaltLambda, EncodableObjectSaltString, EncodableObjectSaltSymbol, EncodableObjectSecretLambda, EncodableObjectSecretString, EncodableObjectSecretSymbol ].each do |klass| yield klass end end end