local pwd = os.getenv('PWD')
local fs = require('fundo.fs')
local path = require('fundo.fs.path')
local async = require('async')


describe('fs module on Unix.', function()
    local samplePath
    setup(function()
        samplePath = path.join(pwd, 'spec', 'sample')
    end)
    describe('synchronous stat file,', function()
        it('stat an existed file.', function()
            local state = fs.statSync(path.join(samplePath, 'foo.txt'))
            assert.equal('file', state.type)
        end)
        it('stat an existed directory.', function()
            local state = fs.statSync(path.join(samplePath, 'empty_dir'))
            assert.equal('directory', state.type)
        end)
        it('stat a non-existed file.', function()
            local state = fs.statSync(path.join(samplePath, 'foo_non_existed.txt'))
            assert.Nil(state)
        end)
    end)
    describe('asynchronous stat file,', function()
        local state
        it('stat an existed file.', function()
            async(function()
                state = await(fs.stat(path.join(samplePath, 'foo.txt')))
                assert.equal('file', state.type)
                done()
            end)
            assert.True(wait())
        end)
        it('stat an existed directory.', function()
            async(function()
                state = await(fs.stat(path.join(samplePath, 'empty_dir')))
                assert.equal('directory', state.type)
                done()
            end)
            assert.True(wait())
        end)
        it('stat a non-existed file.', function()
            async(function()
                state = await(fs.stat(path.join(samplePath, 'foo_non_existed.txt')))
                done()
            end)
            local ok, msg = wait()
            assert.False(ok)
            assert.truthy(msg:match('^ENOENT: no such file or directory'))
        end)
    end)
    describe('asynchronous copy file,', function()
        local dupPath
        setup(function()
            dupPath = path.join(samplePath, '__dup__.txt')
        end)
        after_each(function()
            os.remove(dupPath)
        end)
        it('copy an existed file', function()
            async(function()
                await(fs.copyFile(path.join(samplePath, 'foo.txt'), dupPath))
                done()
            end)
            assert.True(wait())
        end)
        it('copy a non-existed file', function()
            async(function()
                await(fs.copyFile(path.join(samplePath, 'foo_non_existed.txt'), dupPath))
                done()
            end)
            local ok, msg = wait()
            assert.False(ok)
            assert.truthy(msg:match('^ENOENT: no such file or directory'))
        end)
    end)
end)
