#--
# Copyright (c) 2007 Robert S. Thau, Smartleaf, Inc.
# 
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
# 
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
# 
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#++
require File.dirname(__FILE__) + '/../test_helper'
require 'permissions_controller'

# Re-raise errors caught by the controller.
class PermissionsController; def rescue_action(e) raise e end; end

class PermissionsControllerTest < Test::Unit::TestCase

  use_all_fixtures

  def setup
    @controller = PermissionsController.new
    @request    = ActionController::TestRequest.new
    @response   = ActionController::TestResponse.new

    log_in_as users(:ricky)
  end

  def test_post_edit_add_perm

    User.as( users(:universal_grant_guy) ) do
      users(:ricky).role_assignments << 
        RoleAssignment.new( :role => roles( :universal_grant ) )
    end

    ug_perm = permissions(:universal_grant_grants_all)
    assert_equal [ug_perm], users(:ricky).grant_permissions
    assert_equal 0, roles(:ricardo_twiddler).permissions.count

    post :create, 
      :role_id => roles(:ricardo_twiddler).id.to_s,
      :grant_id => ug_perm.id.to_s,
      :permission =>
        { :class_name => 'Product',
          :privilege => 'offer_for_sale',
          :target_owner_id => users(:fred).id.to_s,
          :target_owner_firm_id => firms(:mertz).id.to_s,
          :is_grant => 'false',
          :has_grant_option => 'false' }

    assert_redirected_to edit_role_url( roles(:ricardo_twiddler) )

    roles(:ricardo_twiddler).permissions(:reload)
    assert_equal 1, roles(:ricardo_twiddler).permissions.count
    assert_equal "offer_for_sale products owned by fred, of firm Mertz",
      roles(:ricardo_twiddler).permissions.first.description

  end

  def test_post_edit_kill_perm
    delete :destroy, :role_id => roles(:ricardo_admin).id.to_s,
           :id => permissions(:ricardo_admin_post_create).id.to_s
    assert_redirected_to edit_role_url( roles(:ricardo_admin) )
    assert_nil Permission.find_by_id(permissions(:ricardo_admin_post_create))
  end

end



