LoginSignup
3
0

More than 3 years have passed since last update.

nosetestを実行してくれる簡単なvimプラグインを作ってみる

Last updated at Posted at 2019-12-15

この記事はアラタナアドベントカレンダー2019の16日目の記事です。

ad.png

vim歴半年の新米がvimプラグインを作ってみる記事になります。
変な書き方しちゃってる箇所もあるかと思いますが、ご指摘いただけると嬉しいです。

せっかくなので普段使えるものを作ってみたいということでテストを実行してくれるプラグインを題材にしたいと思います。
筆者はせっかちなのでテストコードを書いたあと下記のように関数ひとつを指定してテストを実行します。

nosetests test_hoge.py:Hogeclass.test_func

これを簡単に実行するプラグインを目指します。

関数名の取得

現在のカーソルより前の位置で最初に検索に引っかかった箇所の関数名を取得します。

function! Get_func_name()
  ?\vdef\stest_[a-z]*
  return split(split(getline('.'), " ")[1], "(")[0]
endfunction

?\vdef\stest_[a-z]*

  • ?:前方向に検索
  • \v:正規表現を使用
  • \s:空白

def test_で始まる関数名を取得しています。

クラス名の取得

同様にクラス名も取得します。

function! Get_class_name()
  ?\vclass\s[a-zA-Z]*
  return split(split(getline('.'), " ")[1], "(")[0]
endfunction

テストコマンド作成


function! Create_test_command()
  let func_name = Get_func_name()
  let class_name = Get_class_name()
  let test_command = "nosetests"." ".expand("%:p").":".class_name.".".func_name." -v"
  return test_command
endfunction

下記の形をむりやり作ってます。

nosetests test_hoge.py:Hogeclass.test_func

テスト実行

テストを実行する関数の記述とコマンドモードで実行できる記述になります。
ExecTest

function! Exec_test()
  let test_command = Create_test_command()
  echo system(test_command)
endfunction

command! ExecTest call Exec_test()

使ってみる

作成したvimscriptファイルを読み込みます

スクリーンショット 2019-12-15 22.58.58.png

ExecTestコマンドが使えるようになるので10行目にカーソルをあわせて使ってみます。

スクリーンショット 2019-12-15 22.57.13.png

test_secondが実行されていますね。カーソルを7行目にあわせて使ってみます。

スクリーンショット 2019-12-15 23.07.01.png

test_firstが実行されました。

まとめ

カーソル下ブロックのテストコードを実行するプラグインを作ってみました。
検索でヒットした箇所に移動する性質を利用したコードになっているのですが、逆に不便なところもあります。
できれば移動せずに実行したいので改善していきたいです。

3
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
0