require_relative '../../spec_helper'
require_relative 'fixtures/file_types'

describe "File.ftype" do
  before :all do
    FileSpecs.configure_types
  end

  it "raises ArgumentError if not given exactly one filename" do
    -> { File.ftype }.should.raise(ArgumentError)
    -> { File.ftype('blah', 'bleh') }.should.raise(ArgumentError)
  end

  it "raises Errno::ENOENT if the file is not valid" do
    -> {
      File.ftype("/#{$$}#{Time.now.to_f}")
    }.should.raise(Errno::ENOENT)
  end

  it "returns a String" do
    FileSpecs.normal_file do |file|
      File.ftype(file).should.is_a?(String)
    end
  end

  it "returns 'file' when the file is a file" do
    FileSpecs.normal_file do |file|
      File.ftype(file).should == 'file'
    end
  end

  it "returns 'directory' when the file is a dir" do
    FileSpecs.directory do |dir|
      File.ftype(dir).should == 'directory'
    end
  end

  it "uses to_path to convert arguments" do
    FileSpecs.normal_file do |file|
      obj = mock('path')
      obj.should_receive(:to_path).and_return(file)
      File.ftype(obj).should == 'file'
    end
  end

  # Both FreeBSD and Windows does not have block devices
  platform_is_not :freebsd, :windows do
    with_block_device do
      it "returns 'blockSpecial' when the file is a block" do
        FileSpecs.block_device do |block|
          File.ftype(block).should == 'blockSpecial'
        end
      end
    end
  end

  platform_is_not :windows do
    it "returns 'characterSpecial' when the file is a char"  do
      FileSpecs.character_device do |char|
        File.ftype(char).should == 'characterSpecial'
      end
    end

    it "returns 'link' when the file is a link" do
      FileSpecs.symlink do |link|
        File.ftype(link).should == 'link'
      end
    end

    it "returns fifo when the file is a fifo" do
      FileSpecs.fifo do |fifo|
        File.ftype(fifo).should == 'fifo'
      end
    end

    it "returns 'socket' when the file is a socket" do
      FileSpecs.socket do |socket|
        File.ftype(socket).should == 'socket'
      end
    end
  end

  platform_is :darwin do
    it "accepts a path in a non-UTF-8, ASCII-compatible encoding containing non-ASCII characters" do
      utf8_path = tmp("file_ftype_utf8_path_\u{3042}.txt")
      # Can fail with UndefinedConversionError if tmp path has non-Shift_JIS chars (e.g. Emojis, Hangul, Cyrillic, accented letters)
      non_utf8_path = utf8_path.encode(Encoding::Windows_31J)

      begin
        touch(utf8_path)
        File.ftype(non_utf8_path).should == 'file'
      ensure
        rm_r utf8_path
        rm_r non_utf8_path
      end
    end
  end
end
