repositories / dotfiles

dotfiles

bugabingas dorkfiles

owned by bugabinga

neovim/tests/std/auto_spec.lua

Raw
local auto = require('std.auto')

describe('std.auto', function()
  after_each(function()
    vim.api.nvim_del_augroup_by_name('test_group')
  end)

  describe('group-scoped autocmds (no buffer)', function()
    it('should register and fire a group autocmd', function()
      local fired = false
      auto 'test_group' {
        events = 'User',
        pattern = 'TestEvent',
        command = function() fired = true end,
      }
      vim.cmd('doautocmd User TestEvent')
      assert.is_true(fired)
    end)

    it('should pass group to nvim_create_autocmd', function()
      auto 'test_group' {
        events = 'User',
        pattern = 'TestGroupScoped',
        command = function() end,
      }
      local autocmds = vim.api.nvim_get_autocmds({ group = 'test_group' })
      assert.is_true(#autocmds > 0)
    end)
  end)

  describe('buffer-local autocmds (with buffer)', function()
    it('should fire a buffer-local autocmd', function()
      local buf = vim.api.nvim_create_buf(true, false)
      local fired = false
      auto 'test_group' {
        events = 'BufWinEnter',
        buffer = buf,
        command = function() fired = true end,
      }
      vim.api.nvim_exec_autocmds('BufWinEnter', { buffer = buf })
      assert.is_true(fired)
      vim.api.nvim_buf_delete(buf, { force = true })
    end)

    it('should respect once = true for buffer-local autocmds', function()
      local buf = vim.api.nvim_create_buf(true, false)
      local count = 0
      auto 'test_group' {
        events = 'BufWinEnter',
        buffer = buf,
        once = true,
        command = function() count = count + 1 end,
      }
      vim.api.nvim_exec_autocmds('BufWinEnter', { buffer = buf })
      assert.equals(1, count)
      vim.api.nvim_exec_autocmds('BufWinEnter', { buffer = buf })
      assert.equals(1, count)
      vim.api.nvim_buf_delete(buf, { force = true })
    end)

    it('should auto-clean when buffer is deleted', function()
      local buf = vim.api.nvim_create_buf(true, false)
      auto 'test_group' {
        events = 'BufWinEnter',
        buffer = buf,
        command = function() end,
      }
      vim.api.nvim_buf_delete(buf, { force = true })
      local autocmds = vim.api.nvim_get_autocmds({ event = 'BufWinEnter' })
      local found = false
      for _, a in ipairs(autocmds) do
        if a.buffer == buf then
          found = true
          break
        end
      end
      assert.is_false(found)
    end)
  end)
end)