robin/laufey
git clone https://git.robinwobin.dev/robin/laufey
aa1d8a2702
master
1*dev_test.txt* Nvim 2 3 4 NVIM REFERENCE MANUAL 5 6 7Writing tests for Nvim *dev-test* 8 9 Type |gO| to see the table of contents. 10 11============================================================================== 12Writing tests for Nvim 13 14Nvim has a powerful yet simple test framework. It's approximately 7x better 15than whatever you use at work. 16 17Each test starts a new Nvim process (10-30ms) which is discarded after the 18test finishes. You assert stuff using `t.eq()` and `screen:expect()` (which 19automatically waits as needed). That's pretty much it. 20 21TODO: Expose the test framework as a public interface, for use in 3P plugins: 22https://github.com/neovim/neovim/issues/34592 23 24============================================================================== 25Test framework 26 27Tests are broadly divided into unit tests (`test/unit/`), functional tests 28(`test/functional/`) and old tests (`test/old/testdir/`). 29 30- Unit testing is achieved by compiling the tests as a shared library which is 31 loaded and called by [LuaJit FFI](https://luajit.org/ext_ffi.html). 32- Functional tests are driven by RPC, so they do not require LuaJit (as 33 opposed to Lua). They are essentially "integration" tests, they test the 34 full system. But they are fast. 35 36You can learn [Lua concepts 15 minutes](https://learnxinyminutes.com/docs/lua/), 37see also |lua-guide|. Use any existing test as a template to start writing new 38tests, or see |dev-quickstart|. 39 40Tests are run by the `/cmake/RunTests.cmake` script using the repo-local Lua 41test harness in `/test/harness.lua`. 42For some failures, `./build/nvim.log` (or `$NVIM_LOG_FILE`) may provide insight. 43 44Depending on the presence of binaries (e.g., `xclip`) some tests will be 45skipped. 46 47Harness isolation *dev-test-harness-isolation* 48 49The Lua harness runs all selected spec files in one `nvim -l` process, then 50restores a baseline before each file. For each suite iteration, the file 51boundary baseline is captured after `--helper` is loaded, so helper-provided 52modules and defaults persist across files. 53Helper files are preload-only: they may require modules, set defaults, and 54register suite-end cleanup, but they do not define tests or hooks. 55 56The harness restores `_G`, `package.loaded`, `package.preload`, `arg`, and the 57process environment with the same shallow file boundary model that busted uses. 58 59============================================================================== 60Test Layout 61 62- `/test/benchmark` : benchmarks 63- `/test/functional` : functional tests 64- `/test/unit` : unit tests 65- `/test/old/testdir` : old tests (from Vim) 66- `/test/config` : contains `*.in` files which are transformed into `*.lua` 67 files using `configure_file` CMake command: this is for accessing CMake 68 variables in Lua tests. 69- `/test/includes` : include-files for use by luajit `ffi.cdef` C definitions 70 parser: normally used to make macros not accessible via this mechanism 71 accessible the other way. 72- `/test/*/preload.lua` : modules and defaults preloaded by the harness 73 `--helper` option 74- `/test/**/testutil.lua` : common utility functions in the context of the test 75 runner 76- `/test/**/testnvim.lua` : common utility functions in the context of the 77 test session (RPC channel to the Nvim child process created by clear() for each test) 78- `/test/*/**/*_spec.lua` : actual tests. Files that do not end with 79 `_spec.lua` are libraries like `/test/**/testutil.lua`, except that they have 80 some common topic. 81 82 83============================================================================== 84Running tests *dev-run-test* 85 86EXECUTING TESTS 87 88To run all tests (except "old" tests): > 89 make test 90 91To run only _unit_ tests: > 92 make unittest 93 94To run only _functional_ tests: > 95 make functionaltest 96 97To run functional tests in parallel (used in CI): > 98 cmake --build build --target functionaltest-parallel -j2 99 cmake --build build --target functionaltest-summary 100 101 102LEGACY TESTS 103 104To run all legacy Vim tests: > 105 make oldtest 106 107To run a _single_ legacy test file you can use either: > 108 # Specify only the test file name, not the full path. 109 make oldtest TEST_FILE=test_syntax.vim 110or: > 111 make test/old/testdir/test_syntax.vim 112 113 114DEBUGGING TESTS 115 116- Each test gets a test id which looks like "T123". This also appears in the 117 log file. Child processes spawned from a test appear in the logs with the 118 _parent_ name followed by "/c". Example: > 119 120 DBG 2022-06-15T18:37:45.226 T57.58016.0 UI: flush 121 DBG 2022-06-15T18:37:45.226 T57.58016.0 inbuf_poll:442: blocking... events_enabled=0 events_pending=0 122 DBG 2022-06-15T18:37:45.227 T57.58016.0/c UI: stop 123 INF 2022-06-15T18:37:45.227 T57.58016.0/c os_exit:595: Nvim exit: 0 124 DBG 2022-06-15T18:37:45.229 T57.58016.0 read_cb:118: closing Stream (0x7fd5d700ea18): EOF (end of file) 125 INF 2022-06-15T18:37:45.229 T57.58016.0 on_proc_exit:400: exited: pid=58017 status=0 stoptime=0 126 127- You can set `$GDB` to [run functional tests under gdbserver](https://github.com/neovim/neovim/pull/1527): >sh 128 GDB=1 TEST_FILE=test/functional/api/buffer_spec.lua TEST_FILTER='nvim_buf_set_text works$' make functionaltest 129< 130 Read more about |dev-filter-test|. 131 132 Then, in another terminal: >sh 133 gdb -ex 'target remote localhost:7777' build/bin/nvim 134< 135 If `$VALGRIND` is also set it will pass `--vgdb=yes` to valgrind instead of 136 starting gdbserver directly. 137 138 See `nvim_argv` in `test/functional/testnvim.lua`. 139 140- Hanging tests can happen due to unexpected modal prompts (waiting for user 141 input). The default screen width is 50 columns. 142 - Commands that try to print lines longer than 50 columns in the cmdline, 143 e.g. `:edit very...long...path`, will trigger the hit-enter prompt. Try 144 using a shorter path, or `:silent edit`. 145- If you can't figure out what is going on, try to visualize the screen. Put 146 this at the beginning of your test: > 147 local Screen = require('test.functional.ui.screen') 148 local screen = Screen.new() 149 screen:attach() 150< Then put `screen:snapshot_util()` anywhere in your test. See the comments in 151 `test/functional/ui/screen.lua` for more info. 152 153DEBUGGING LUA TEST CODE 154 155Debugging Lua test code is a bit involved. Get your shopping list ready, you'll 156need to install and configure: 157 1581. [nvim-dap](https://github.com/mfussenegger/nvim-dap) 1592. [local-lua-debugger-vscode](https://github.com/mfussenegger/nvim-dap/wiki/Debug-Adapter-installation#local-lua-debugger-vscode) 1603. [nlua](https://github.com/mfussenegger/nlua) 1614. [one-small-step-for-vimkind](https://github.com/jbyuki/one-small-step-for-vimkind) (called `osv`) 1625. An `nlua` command in `$PATH`. 163 164 165The setup roughly looks like this: > 166 167 ┌─────────────────────────┐ 168 │ nvim used for debugging │◄────┐ 169 └─────────────────────────┘ │ 170 │ │ 171 ▼ │ 172 ┌─────────────────┐ │ 173 │ local-lua-debug │ │ 174 └─────────────────┘ │ 175 │ │ 176 ▼ │ 177 ┌─────────┐ │ 178 │ nlua │ │ 179 └─────────┘ │ 180 │ │ 181 ▼ │ 182 ┌───────────┐ │ 183 │ test-case │ │ 184 └───────────┘ │ 185 │ │ 186 ▼ │ 187 ┌────────────────────┐ │ 188 │ nvim test-instance │ │ 189 └────────────────────┘ │ 190 │ ┌─────┐ │ 191 └──►│ osv │─────────────────┘ 192 └─────┘ 193 194 195With these installed you can use a configuration like this: > 196 197 local dap = require("dap") 198 199 200 local function free_port() 201 local tcp = vim.loop.new_tcp() 202 assert(tcp) 203 tcp:bind('127.0.0.1', 0) 204 local port = tcp:getsockname().port 205 tcp:shutdown() 206 tcp:close() 207 return port 208 end 209 210 211 local name = "nvim-test-case" -- arbitrary name 212 local config = { 213 name = name, 214 215 -- value of type must match the key used in `dap.adapters["local-lua"] = ...` from step 2) 216 type = "local-lua", 217 218 request = "launch", 219 cwd = "${workspaceFolder}", 220 program = { 221 command = "nlua", 222 }, 223 args = { 224 "-l", 225 "test/runner.lua", 226 "--helper=test/functional/preload.lua", 227 "--lpath=build/?.lua", 228 "--lpath=?.lua", 229 230 -- path to file to debug, could be replaced with a hardcoded string 231 function() 232 return vim.api.nvim_buf_get_name(0) 233 end, 234 235 -- You can filter to specific test-case by adding: 236 -- '--filter="' .. test_case_name .. '"', 237 }, 238 env = { 239 OSV_PORT = free_port 240 } 241 } 242 243 -- Whenever the config is used it needs to launch a second debug session that attaches to `osv` 244 -- This makes it possible to step into `exec_lua` code blocks 245 setmetatable(config, { 246 247 __call = function(c) 248 ---@param session dap.Session 249 dap.listeners.after.event_initialized["nvim_debug"] = function(session) 250 if session.config.name ~= name then 251 return 252 end 253 dap.listeners.after.event_initialized["nvim_debug"] = nil 254 vim.defer_fn(function() 255 dap.run({ 256 name = "attach-osv", 257 type = "nlua", -- value must match the `dap.adapters` definition key for osv 258 request = "attach", 259 port = session.config.env.OSV_PORT, 260 }) 261 end, 500) 262 end 263 264 return c 265 end, 266 }) 267 268 269You can either add this configuration to your `dap.configurations.lua` list as 270described in `:help dap-configuration` or create it dynamically in a 271user-command or function and call it directly via `dap.run(config)`. The latter 272is useful if you use treesitter to find the test case around a cursor location 273with a query like the following and set the `--filter` property to it. >query 274 275 (function_call 276 name: (identifier) @name (#any-of? @name "describe" "it") 277 arguments: (arguments 278 (string) @str 279 ) 280 ) 281 282Limitations: 283 284- You need to add the following boilerplate to each spec file where you want to 285 be able to stop at breakpoints within the test-case code: > 286 if os.getenv("LOCAL_LUA_DEBUGGER_VSCODE") == "1" then 287 require("lldebugger").start() 288 end 289< This is a local-lua-debugger limitation. 290- You cannot step into code of files which get baked into the nvim binary 291 (such as `_core/*.lua` and `inspect.lua`). 292 293 294------------------------------------------------------------------------------ 295Filtering tests *dev-filter-test* 296 297FILTER BY NAME 298 299Tests can be filtered by setting a pattern of test name to `TEST_FILTER` or `TEST_FILTER_OUT`. > 300 301 it('foo api',function() 302 ... 303 end) 304 it('bar api',function() 305 ... 306 end) 307 308To run only test with filter name: > 309 TEST_FILTER='foo.*api' make functionaltest 310 311To run all tests except ones matching a filter: > 312 TEST_FILTER_OUT='foo.*api' make functionaltest 313 314FILTER BY FILE 315 316To run a _specific_ unit test: > 317 TEST_FILE=test/unit/foo.lua make unittest 318 319or > 320 cmake -E env "TEST_FILE=test/unit/foo.lua" cmake --build build --target unittest 321 322To run a _specific_ functional test: > 323 TEST_FILE=test/functional/foo.lua make functionaltest 324 325or > 326 cmake -E env "TEST_FILE=test/functional/foo.lua" cmake --build build --target functionaltest 327 328To _repeat_ a test: > 329 TEST_ARGS="--repeat=100 --no-keep-going" TEST_FILE=test/functional/foo_spec.lua make functionaltest 330 331or > 332 cmake -E env "TEST_FILE=test/functional/foo_spec.lua" cmake -E env TEST_ARGS="--repeat=100 --no-keep-going" cmake --build build --target functionaltest 333 334FILTER BY TAG 335 336Tests can be "tagged" by adding `#` before a token in the test description. > 337 338 it('#foo bar baz', function() 339 ... 340 end) 341 it('#foo another test', function() 342 ... 343 end) 344 345To run only the tagged tests: > 346 TEST_TAG=foo make functionaltest 347 348NOTE: 349 350- `TEST_FILE` is not a pattern string like `TEST_TAG` or `TEST_FILTER`. The 351 given value to `TEST_FILE` must be a path to an existing file. 352- Both `TEST_TAG` and `TEST_FILTER` filter tests by the string descriptions 353 found in `it()` and `describe()`. 354 355 356============================================================================== 357Writing tests *dev-write-test* 358 359GUIDELINES 360 361- CI runs tests in parallel via the `functionaltest-parallel` cmake target. 362- The Nvim test instance CWD is isolated to per "test group" (see 363 `WORKING_DIRECTORY` in `cmake/RunTests.cmake`), so tests can write files to 364 CWD without interfering with other tests running in parallel. 365- Luajit needs to know about type and constant declarations used in function 366 prototypes. The 367 [testutil.lua](https://github.com/neovim/neovim/blob/master/test/unit/testutil.lua) 368 file automatically parses `types.h`, so types used in the tested functions 369 could be moved to it to avoid having to rewrite the declarations in the test 370 files. 371 - `#define` constants must be rewritten `const` or `enum` so they can be 372 "visible" to the tests. 373- Use `pending()` or `t.skip()` to skip tests. 374 - Example: https://github.com/neovim/neovim/commit/5c1dc0fbe7388528875aff9d7b5055ad718014de#diff-bf80b24c724b0004e8418102f68b0679R18 375 - Note: If a test is skipped because of a non-actionable reason, we don't 376 want it to appear in the "pending" list. Include "N/A" in the skip 377 description, then it won't be added to the "pending" list. For example, if 378 a test is skipped because it's running on a non-LuaJit system, including 379 it in the "pending" list is just noise. Thus, its pending reason should 380 say "N/A": > 381 pending('N/A: missing LuaJIT FFI') 382< 383 - Do not silently skip the test with `if-else`. If a functional test depends 384 on some external factor (e.g. the existence of `md5sum` on `$PATH`), _and_ 385 you can't mock or fake the dependency, then skip the test via `pending()` 386 if the external factor is missing. This ensures that the _total_ 387 test-count (success + fail + error + pending) is the same in all 388 environments. 389 - Note: `pending()` is ignored if it is missing an argument, unless it is 390 [contained in an `it()` block](https://github.com/neovim/neovim/blob/d21690a66e7eb5ebef18046c7a79ef898966d786/test/functional/ex_cmds/grep_spec.lua#L11). 391 Provide empty function argument if the `pending()` call is outside `it()` 392 Example: https://github.com/neovim/neovim/commit/5c1dc0fbe7388528875aff9d7b5055ad718014de#diff-bf80b24c724b0004e8418102f68b0679R18 393 394WHERE TESTS GO 395 396Tests in `/test/unit` and `/test/functional` are divided into groups by the 397semantic component they are testing. 398 399- Unit tests (`test/unit/`) should match 1-to-1 with the structure of 400 `src/nvim/`, because they are testing functions directly. E.g. unit-tests 401 for `src/nvim/undo.c` should live in `test/unit/undo_spec.lua`. 402- Functional tests (`test/functional/`) are higher-level (plugins, UI, user 403 input) than unit tests; they are organized by concept. 404 - Try to find an existing `test/functional/*/*_spec.lua` group that makes 405 sense, before creating a new one. 406 407 408------------------------------------------------------------------------------ 409Fixing tests *dev-fix-test* 410 411FIXING HARNESS WARNINGS 412 413> Nvim session T123 took 2000 milliseconds to exit 414> This indicates a likely problem with the test even if it passed! 415 416This may indicate a leak, because Nvim waits on uv handles before exiting. 417Example: https://github.com/neovim/neovim/pull/35768 418 419 420FIXING LINT FAILURES 421 422`make emmylua-check` runs EmmyLua on the runtime Lua code, using `.emmyrc.json`. 423The checker is downloaded automatically. Enable more checks incrementally by 424removing codes from `diagnostics.disable` and fixing the resulting diagnostics. 425 426If an EmmyLua warning must be ignored, specify the warning code. Example: >lua 427 428 ---@diagnostic disable-next-line: unused 429 430https://github.com/EmmyLuaLs/emmylua-analyzer-rust 431 432Ignore the smallest applicable scope (e.g. inside a function, not at the top of 433the file). 434 435 436============================================================================== 437Configuration *dev-test-config* 438 439(TODO: clean this up, too many variables and some of them are not used anymore.) 440 441Test behaviour is affected by environment variables. Currently supported 442(Functional, Unit, Benchmarks) (when Defined; when set to _1_; when defined, 443treated as Integer; when defined, treated as String; when defined, treated as 444Number; !must be defined to function properly): 445 446- `TEST_ARGS` (F) (U): arguments forwarded to the local test harness. 447 448- `CC` (U) (S): specifies which C compiler to use to preprocess files. 449 Currently only compilers with gcc-compatible arguments are supported. 450 451- `GDB` (F) (D): makes nvim instances to be run under `gdbserver`. It will be 452 accessible on `localhost:7777`: use `gdb build/bin/nvim`, type `target remote :7777` inside. 453 454- `GDBSERVER_PORT` (F) (I): overrides port used for `GDB`. 455 456- `LOG_DIR` (FU) (S!): specifies where to seek for valgrind and ASAN log files. 457 458- `VALGRIND` (F) (D): makes nvim instances to be run under `valgrind`. Log 459 files are named `valgrind-%p.log` in this case. Note that non-empty valgrind 460 log may fail tests. Valgrind arguments may be seen in 461 `/test/functional/testnvim.lua`. May be used in conjunction with `GDB`. 462 463- `VALGRIND_LOG` (F) (S): overrides valgrind log file name used for `VALGRIND`. 464 465- `TEST_COLORS` (F) (U) (D): enable pretty colors in test runner. Set to true by default. 466 467- `TEST_SKIP_FRAGILE` (F) (D): makes test suite skip some fragile tests. 468 469- `TEST_TIMEOUT` (FU) (I): specifies maximum time, in seconds, before the test 470 suite run is killed 471 472- `NVIM_TEST` (FU) (D): lets Nvim process detect that it is running in a test. 473 474- `NVIM_LUA_NOTRACK` (F) (D): disable reference counting of Lua objects 475 476- `NVIM_PRG` (F) (S): path to Nvim executable (default: `build/bin/nvim`). 477 478- `NVIM_TEST_MAIN_CDEFS` (U) (1): makes `ffi.cdef` run in main process. This 479 raises a possibility of bugs due to conflicts in header definitions, despite 480 the counters, but greatly speeds up unit tests by not requiring `ffi.cdef` to 481 do parsing of big strings with C definitions. 482 483- `NVIM_TEST_PRINT_I` (U) (1): makes `cimport` print preprocessed, but not yet 484 filtered through `formatc` headers. Used to debug `formatc`. Printing is done 485 with the line numbers. 486 487- `NVIM_TEST_PRINT_CDEF` (U) (1): makes `cimport` print final lines which will 488 be then passed to `ffi.cdef`. Used to debug errors `ffi.cdef` happens to 489 throw sometimes. 490 491- `NVIM_TEST_PRINT_SYSCALLS` (U) (1): makes it print to stderr when syscall 492 wrappers are called and what they returned. Used to debug code which makes 493 unit tests be executed in separate processes. 494 495- `NVIM_TEST_RUN_FAILING_TESTS` (U) (1): makes `itp` run tests which are known 496 to fail (marked by setting third argument to `true`). 497 498- `NVIM_TEST_CORE_*` (FU) (S): a set of environment variables which specify 499 where to search for core files. Are supposed to be defined all at once. 500 501- `NVIM_TEST_CORE_GLOB_DIRECTORY` (FU) (S): directory where core files are 502 located. May be `.`. This directory is then recursively searched for core 503 files. Note: this variable must be defined for any of the following to have 504 any effect. 505 506- `NVIM_TEST_CORE_GLOB_RE` (FU) (S): regular expression which must be matched 507 by core files. E.g. `/core[^/]*$`. May be absent, in which case any file is 508 considered to be matched. 509 510- `NVIM_TEST_CORE_EXC_RE` (FU) (S): regular expression which excludes certain 511 directories from searching for core files inside. E.g. use `^/%.deps$` to not 512 search inside `/.deps`. If absent, nothing is excluded. 513 514- `NVIM_TEST_CORE_DB_CMD` (FU) (S): command to get backtrace out of the 515 debugger. E.g. `gdb -n -batch -ex "thread apply all bt full" 516 "$_NVIM_TEST_APP" -c "$_NVIM_TEST_CORE"`. Defaults to the example command. 517 This debug command may use environment variables `_NVIM_TEST_APP` (path to 518 application which is being debugged: normally either nvim or luajit) and 519 `_NVIM_TEST_CORE` (core file to get backtrace from). 520 521- `NVIM_TEST_CORE_RANDOM_SKIP` (FU) (D): makes `check_cores` not check cores 522 after approximately 90% of the tests. Should be used when finding cores is 523 too hard for some reason. Normally (on OS X or when 524 `NVIM_TEST_CORE_GLOB_DIRECTORY` is defined and this variable is not) cores 525 are checked for after each test. 526 527- `NVIM_TEST_INTEG` (F) (D): enables integration tests that makes real network 528 calls. By default these tests are skipped. When set to `1`, tests requiring external 529 HTTP requests (e.g `vim.net.request()`) will be run. 530 531- `NVIM_TEST_RUN_TESTTEST` (U) (1): allows running 532 `test/unit/testtest_spec.lua` used to check how testing infrastructure works. 533 534- `NVIM_TEST_TRACE_LEVEL` (U) (N): specifies unit tests tracing level: 535 - `0` disables tracing (the fastest, but you get no data if tests crash and 536 no core dump was generated), 537 - `1` leaves only C function calls and returns in the trace (faster than 538 recording everything), 539 - `2` records all function calls, returns and executed Lua source lines. 540 541- `NVIM_TEST_TRACE_ON_ERROR` (U) (1): makes unit tests yield trace on error in 542 addition to regular error message. 543 544- `NVIM_TEST_MAXTRACE` (U) (N): specifies maximum number of trace lines to 545 keep. Default is 1024. 546 547- `OSV_PORT`: (F): launches `osv` listening on the given port within nvim test 548 instances. 549 550 551 vim:tw=78:ts=8:sw=4:et:ft=help:norl: