TeraTermマクロで対話型コマンドのテスト

定期的に行われる対話型コマンドの回帰テスト。バッチ化できないからって毎度手動でやるのはアホらしいよね。というわけで、TeraTermマクロでがんばってみる。

まずは簡単なテスト対象。

#include <stdio.h>

int main()
{
  int n = 0;

  do {
    printf("in => ");
    scanf("%d", &n);
    if (n == 1) {
      printf("Hello, world%d\n", n);
    }
    else {
      printf("error%d\n", n);
    }
  }
  while (n != 1);

  return 0;
}

プロンプトを表示して入力を待つ。「1」を入力したらプログラムを終了する。入力値に応じて文字列を出力する。かなり手抜き。

そして、上記を実行するTeraTermのマクロ。

goto main

;*************************
; 文字列を待つコマンド
prompt = ''    ; 引 数:監視文字列
:wait_plus
  match0 = ''  ; 戻り値:ヒット文字列(最後)
  match1 = ''  ; 戻り値:ヒット文字列(一つ前)
  setsync 1
  timeout_old = timeout
  timeout = 1

  result = 0
  while result <= 0
    recvln

    ; ヒット文字列の退避
    strlen match0
    strcopy match0 0 result match1
    strlen inputstr
    strcopy inputstr 0 result match0

    strscan inputstr prompt
  endwhile

  timeout = timeout_old
  setsync 0
  return
;*************************

;*************************
:main
  connect '192.168.xxx.xxx'

  ; set username
  Username = 'hoge'
  getpassword 'password.dat' 'mypassword' Password
  
  ; login
  wait   'login:'
  sendln Username
  wait   'Password:'
  sendln Password
  
  wait   '$'
  sendln './tmp/a.out'
  
  prompt = 'in =>'
  call wait_plus
  sendln '2'

  prompt = 'in =>'
  call wait_plus
  strscan match1 'error'
  if result <> 0 then
    ; 2を入力すると'error...'になるはず。
  else
    messagebox match1 "ng"
  endif
  sendln '1'

  prompt = '$'
  call wait_plus
  strscan match1 'Hello, world1'
  if result <> 0 then
    ; 1を入力すると'Hello, world1'になるはず。
  else
    messagebox match1 "ng"
  endif
  sendln 'exit'
  
  end
;*************************

Telnetでログインして対話的に実行する。実行結果はこんな感じ。

Ubuntu 8.04.4 LTS
ubuntu-vm login: hoge
Password:

The programs included with the Ubuntu system are free software;
the exact distribution terms for each program are described in the
individual files in /usr/share/doc/*/copyright.

Ubuntu comes with ABSOLUTELY NO WARRANTY, to the extent permitted by
applicable law.

To access official Ubuntu documentation, please visit:
http://help.ubuntu.com/
hoge@ubuntu-vm:~$ ./tmp/a.out
in => 2
error2
in => 1
Hello, world1
hoge@ubuntu-vm:~$

TeraTermマクロ使いにくい…。自由にツールが選べるならPoderosaにしたいところ。もしくはNet::Telnetやexpectなんかも使えそう。