junegunn / vader.vim

A simple Vimscript test framework
589 stars 40 forks source link

Can Vader test imported Vim9 functions? #226

Open igbanam opened 1 year ago

igbanam commented 1 year ago

I have a function which checks that some string starts with another string in my utils.vim

# Checks if the left string starts with the right
export def StartsWith(longer: string, shorter: string): bool
  if (shorter->len() > longer->len())
    return false
  endif

  var right_bound = shorter->len() - 1

  return longer[0 : right_bound] ==# shorter
enddef

culled from https://vi.stackexchange.com/a/29063

I want to write a test that this works, so I create a utils.vader with the following content

Execute (Forza):
  import getcwd() .. '/utils.vim'
  Assert v:true, 'vim'->utils.StartsWith('vi')

:h vim9-import allows us use the exported functions from the imported script in the current script's scope. :h getcwd() is there to ensure I'm loading the right file.

The error I get back hints that the script wasn't loaded.

Starting Vader: 1 suite(s), 1 case(s)
  Starting Vader: /Users/igbanam/projects/X/utils.vader
    (1/1) [EXECUTE] Linter
    (1/1) [EXECUTE] (X) Vim(call):E121: Undefined variable: utils
      > function test#run[27]..test#execute[23]..test#shell[19]..test#strategy#vimscript[1]..vader#run[63]..<SNR>244_run[42]..<SNR>244_execute[2]..vader#window#execute[11]..script /private/var/folders/bd/2lzxs5dn6rqg5xdpbk9m52pc0000gn/T/vJFrhtt/18, line 2
  Success/Total: 0/1
Success/Total: 0/1 (assertions: 0/0)
Elapsed time: 0.04 sec.

Any ideas?

igbanam commented 1 year ago

If I introduce a global function like so

def g:ForTesting_StartsWith(longer: string, shorter: string): bool
  returns longer->StartsWith(shorter)
enddef

Then I can write the utils.vader like so

Do (Load the File):
  source utils.vim

Execute
  Assert v:true, 'vim'->g:ForTesting_StartsWith('vi')

…and this succeeds

What I'm trying to stay away from is introducing a global function for every function I would like to test in my plugin. It feels like Java's @VisibleForTesting, but polluting the global scope.