require File.dirname(__FILE__) + '/../test_helper'
require 'search_controller'

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

class SearchControllerTest < Test::Unit::TestCase
  fixtures :directories, :variables, :keyword_attributes

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

  # Replace this with your real tests.
  def test_index
    get :index
    assert_response :success
    assert_tag :tag => "div", :attributes => {:id => "dir"}
  end

  def test_children
    id = 1
    xhr :get, :children, {:id => id}
    assert_response :success
    dir = Directory.find(id)
    assert_equal dir, assigns(:parent)
    assert_equal dir.children, assigns(:dirs)
    assert_equal dir.variables, assigns(:variables)

    id = 1000
    xhr :get, :children, {:id => id}
    assert_response :success
    assert_equal "", @response.body

    id = 1
    xhr :get, :children, {:id => id, :details => true}
    assert_response :success
    dir = Directory.find(id)
    assert_equal dir, assigns(:parent)

    id = 1000
    xhr :get, :children, {:id => id, :details => true}
    assert_response :success
    assert_equal "", @response.body
  end

  def test_clear_tree
    get :clear_tree
    assert_nil session[:dir_tree_in_search]
    assert_response :redirect
    assert_redirected_to :action => :index
  end

  def test_add_to_list
    var_id = 1
    get :add_to_list, {:id => var_id, :type => "var"}
    assert_response :redirect
    assert_redirected_to :controller => "analysis"
    var = Variable.find(var_id)
    assert session[:variables_list].include?(var)

    var_id = 1000
    session[:variables_list] = nil
    get :add_to_list, {:id => var_id, :type => "var"}
    assert_redirected_to :controller => "analysis"
    assert_nil session[:variables_list]

    dir_id = 6
    session[:variables_list] = nil
    get :add_to_list, {:id => dir_id, :type => "dir"}
    assert_redirected_to :controller => "analysis"
    assert_equal Variable.find(:all, :conditions => ["directory_id = ?",dir_id]).length, session[:variables_list].length

    dir_id = 1000
    session[:variables_list] = nil
    get :add_to_list, {:id => dir_id, :type => "dir"}
    assert_redirected_to :controller => "analysis"
    assert_nil session[:variables_list]
  end

end
