Showing posts with label ruby. Show all posts
Showing posts with label ruby. Show all posts

Thursday, February 4, 2010

Death Agony!!!

Sometime I use many PC for automation integration testing.
But it is difficult to manage which one down by error.
So when some PC down,the PC death agony! by skype.
This code will death agony and vomit log.

# death_agony.rb
#! ruby -Ku
require 'rubygems'
require 'win32ole'
require 'kconv'

$KCODE = 'UTF8'
@MACHINE = ARGV[0]
@GOD = ARGV[1]

@oCom=WIN32OLE.new('AutoItX3.Control')
@oSkype=WIN32OLE.new('Skype4COM.skype')
raise "Please start skype" @oSkype.Client.IsRunning != true

death_agnoy = IO.read('errIO.txt')
@oSkype.SendMessage(@GOD, "Death Agony from #{@MACHINE} at #{Time.now}\n" + death_agony)
sleep(3)

@oUser = @oSkype.User(@GOD)
@oCall = @oSkype.PlaceCall(@oUser.Handle)
@oCall.Status

And catch exception in rake task(who don't use rake for testing?)

# rake.rb
# setup >(rake your_task pc=a_one_of_sacrifice p=where_to_agony) 1> errIO.txt
task :hell_grinder do
begin
ruby "death_test.rb "
rescue
p "ring ring ring..."
ruby "death_agony.rb " + ENV['pc'] + " " + ENV['p']
end
end

Then you can hear death agony from each sacrifice.
*Don't forget regsvr skype dll:here down load link
How to regist it.
> regsvr32 -that skype dll-
Ahhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh........

Sunday, November 29, 2009

How to select ComboBox

How to select ComboBox by AutoIt.exe from ruby
Give parameter to select combobox exe.


### select_year_combobox.au3 ###
WinActivate("Configuration")
Global Const $CB_SETCURSEL = 0x14E
$h_combobox = ControlGetHandle("Configuration", "", "[CLASS:WindowsForms10.COMBOBOX.app.0.378734a; INSTANCE:2]")
$i_index = $CMDLINE[1]
DllCall("user32.dll", "int", "SendMessage", "hwnd", $h_combobox, "int", $CB_SETCURSEL, "int", $i_index, "int", 0)


ControlGetHandle("Configuration", "", "[CLASS:WindowsForms10.COMBOBOX.app.0.378734a; INSTANCE:2]")
ControlGetHandle(<app title>, "", <select combobox instance>).
<select combobox instance> is easy to know by AutoIt Window Info app.


### select_combobox.rb ###
select_year_exe = File.expand_path(File.dirname(__FILE__) + "/select_year_combobox.exe")
year = 1 # ex. index 1 = 2005
system("#{select_year_exe} #{year}")


>ruby select_combobox.rb # app will choose index 1 from combobox.
>select_year_combobox.exe 1 # app will choose index 1 from combobox.

Wednesday, November 11, 2009

Skype mood to twitter by COM

Skype mood to twitter.
Skypeのムードをtwitterにpost。

on windowsXP
requirement

Useage
cmd.exe
>gem install twitter4r
>regsvr32 Skype4COM.dll <--when popup dialog,should 'OK'
>ruby mooding.rb
then every 5 sec. ruby check skype mood and updated at that time,post it to twitter.
だいたい5秒おきに、skypeのムードが更新されたか確認して、されてれば、twitterにポストします。下記コードのみ。
for stopping,止め方、Ctrl+C

#! ruby -Ku
require 'rubygems'
require 'win32ole'
require 'twitter'
require 'kconv'

$KCODE = 'UTF8'

@oTwitter = Twitter::Client.new
twit_id = ARGV[0]
twit_pwd = ARGV[1]
if @oTwitter.authenticate?(twit_id, twit_pwd) == true then
p 'OK auth'
else
raise 'ID,Passwd or both is not collect'
end

@oSkype=WIN32OLE.new('Skype4COM.skype')
mood = nil # Anyway 1st time twit mood
loop do
if @oSkype.Client.IsRunning != true then
raise "Please start skype"
else
end

if @oSkype.CurrentUserProfile.MoodText.toutf8 != mood then
mood = @oSkype.CurrentUserProfile.MoodText.toutf8
@oTwitter = Twitter::Client.new(:login => twit_id, :password => twit_pwd)
@oTwitter.status(:post, mood)
else
sleep(5) # check mood update every almost 5sec.
end
end

Wednesday, November 4, 2009

Integrate Watir Rspec for long story testing and force test sequence.

WatirとRspecでテストケースなが~いテストをちょっと効率良く行う。
rspecでテストの順番を指定したい場合が多く、この方法は使えると。
レポートはhtmlで出力。


# spec/test_spec.rb
#! ruby -Ku
#!/usr/bin/env ruby
require 'spec_helper'

$KCODE = 'UTF8'

shared_examples_for "トップ画面にいることの確認" do
it "ログインしてくださいが表示されていること" do
@ie = Watir::IE.new
@ie.goto("#{$testDomain}/foo/index.aspx")
@ie.text.should include('ログインしてください')
end
end

shared_examples_for "ログインできることの確認" do
it "ログインできること、つまりログアウトの表示がされていること" do
@ie = Watir::IE.attach(:title,/.*/)
@ie.text_field(:id, 'account').set('foo')
@ie.text_field(:id, 'password').set('bar')
@ie.button(:xpath, '//td[2]/input').click
@ie.text.should include('ログアウト')
end
end

shared_examples_for "パスワード変更ができてログインできる事の確認" do
it "パスワード変更ができてログインできる事" do
@ie = Watir::IE.attach(:title,/.*/) #このattachで前のテストのIEインスタンスを使用することができる。んで続きが行える。
@ie.text_field(:id, 'CurrentPassword').set('bar')
@ie.text_field(:id,'NewPassword').set('woo')
@ie.text_field(:id,'ConfirmPassword').set('woo')
@ie.button(:name, 'Submit').click_no_wait
@autoit=WIN32OLE.new('AutoItX3.Control')
@autoit.WinWait('Windows Internet Explorer','',10).should == 1
# when dialog(confirm change pwd.), return 1.
@autoit.WinActive('Windows Internet Explorer')
@autoit.ControlClick('Windows Internet Explorer','','OK')
@ie.link(:text, 'ログアウト').click
@ie.text.should include('ログインしてください')
@ie.text_field(:id, 'account').set('foo')
@ie.text_field(:id, 'password').set('woo')
@ie.button(:xpath, '//td[2]/input').click
@ie.text.should include('ログアウト')
end
end

describe "OreOre site long story" do
it_should_behave_like "トップ画面にいることの確認"
it_should_behave_like "ログインできることの確認"
it_should_behave_like "パスワード変更ができてログインできる事の確認"
  # この順番に行われる。
  # describeでどんどんテストケースを追加すると、順番は思ったようにいかない。
# たぶん、test/unitと同じで名前のキャラコード順になる。(たぶん)
end


# spec/spec.opts
#! ruby -Ku
#!/usr/bin/env ruby
--format html:spec/doc/rspec_report.html
--loadby mtime
--colour
--reverse


# spec/spec_helper.rb
#! ruby -Ku
#!/usr/bin/env ruby
$LOAD_PATH.push File.expand_path('../../lib',__FILE__)

require 'rubygems'
require 'spec'
require 'watir'
require 'win32ole'
require 'redgreen'

WIN32OLE.codepage = WIN32OLE::CP_UTF8
#test target domain
$testDomain = 'http://foo.org'


# Rakefile.rb
require 'rake'
require 'spec/rake/spectask'

task :default => [:help]

desc "foo long Story Test"
task :spec do
Spec::Rake::SpecTask.new do |t|
t.spec_files = FileList['spec/*_spec.rb']
t.spec_opts = ['--options', "spec/spec.opts"]
end
end

UTF8のサイトのテストです。

Wednesday, October 28, 2009

Cucumber Watir Rspec Mocha, How to add helper module to cucumber.

Cucumber with Watir



# features/support/env.rb
require 'spec/expectations'

if ENV['FIREWATIR']
require 'firewatir'
Browser = FireWatir::Firefox
else
case RUBY_PLATFORM
when /darwin/
require 'safariwatir'
Browser = Watir::Safari
when /win32|mingw/
require 'watir'
Browser = Watir::IE
when /java/
require 'celerity'
Browser = Celerity::Browser
else
raise "This platform is not supported (#{PLATFORM})"
end
end

# "before all"
browser = Browser.new

Before do
@browser = browser
end

# "after all"
at_exit do
browser.close
end


How to add helper modlue



# features/support/foo_helper.rb
module Foo
def zip_code(pref_name)
if pref_name == 'local'
"123-4567"
else
"Pls. ask postman"
end
end
end
World(Foo)


mocha integration.



# features/support/mocha_helper.rb
require "mocha"

World(Mocha::API)

Before do
mocha_setup
end

After do
begin
mocha_verify
ensure
mocha_teardown
end
end

日本語のFeatureの場合、win32 コンソールではひどいが、htmlに結果を出力すればOK。
例えば、

# config/cucumber.yml
default: --format profile features
html_report: --format progress --format html --out=features_report.html features

で、
C:\あ>cucumber -l ja --profile html_report features/send_tera_mail.feature
で実行すれば、ブラウザでは文字化けしない。
他のサイトでもいろいろ試しているようだけど、コンソールではきびしい。

Friday, October 23, 2009

How to stop SAX parse on libxml-ruby

Stop SAX parse

Does anybody know some stop method?




require 'rubygems'
require 'libxml'
include LibXML

class PostCallbacks
include XML::SaxParser::Callbacks

def on_start_element(element, attributes)
if /usr/ =~ element
p element
raise 'stop!'
end
end


end

parser = XML::SaxParser.file('test.xml')
parser.callbacks = PostCallbacks.new
begin
parser.parse
rescue
p 'hard stop'
end


It will return 1st <usr> then stop.

Thursday, October 8, 2009

invoke &&

Stuck in && place


1st code:When foo_text does not include 'woo',
But always show "It is great movie".

some_str = foo_text.include?('woo') ? 'madam' : ''
if @jekyll_hyde.include?('one-thirty-four' && some_str)
then puts "It is great movie"
else puts "Please check it out again"
end


This below code works well

some_str = foo_text.include?('woo') ? 'madam' : ''
if @jekyll_hyde.include?(some_str && 'one-thirty-four')
then puts "It is great movie"
else puts "Please check it out again"
end


By the way,really good movie that is.

Monday, September 28, 2009

SJIS and UTF8

Stuck in chr encoding!


Encode Situation.
target site : UTF-8
test data : SJIS(CP932)


source file encode:sjis


#! ruby -ks
~some code~
WIN32OLE.codepage = WIN32OLE::CP_UTF8 # -> for target site encode
# string for ie
some_str = 'SJIS str 日本語です。'
give_str = some_str.toutf8


blogger sanitized my code that's why 2byte chr.
なぜ、こんなことになってしまったか?
読み込むCSVがCP932で書かれていて、これは変更できない制限がある。
テストするサイトはUTF8のエンコーディングで、これも変更できない制限がある。
で、CSVのデータを読み込むときに-kuだと、化ける。
-ksで読み込んで、toutf8でエンコードして、WIN32OLE::CP_UTF8で、
ieインスタンスからutf8でもらって$KCODE=UTF8でregexpすることに
必要だった。
他に良い、方法あるのか模索中

Sunday, September 27, 2009

upcase!

  • When I use upcase! for array in regexp,I got error.

  • ex.)

    str = 'ID5'
    str.ucase # -> ID5
    str.upcase! # -> nil

  • When I use option -i(ignore case) for array in regexp,I got error.

  • ex.)

    str = 'AaA'
    /^#{str}$/ =~ 'AAA' # -> nil
    /^#{str}$/i =~ 'AAA' # -> nil (This is strange)
    /^#{str.upcase!}$/ =~ 'AAA' # -> nil (This is also strange)
    /^#{str.upcase}$/ =~ 'AAA' # -> 0

    Thursday, September 3, 2009

    redmine & git repo on debian

    1.setup redmine

    普通にrubyの環境があって、passengerが入ってて、redmineが/var/wwwの下に展開されています。
    サーバのホスト名:base08。
    セットアップしているマシンのユーザがtknv。
    #/etc/apache2/httpd.conf
    LoadModule passenger_module /home/tknv/.gem/ruby/1.8/gems/passenger-2.2.4/ext/apache2/mod_passenger.so
    PassengerRoot /home/tknv/.gem/ruby/1.8/gems/passenger-2.2.4
    PassengerRuby /usr/bin/ruby1.8

    PassengerDefaultUser www

    ServerName base08
    DocumentRoot /var/www/redmine/public


    で、redmineで使用するdbの準備が完了していれば、http://base08でredmineが表示されるはず。
    表示されないようだったらサイトで確認。
    サーバで/var/log/apache2のログを見てもおかしいところがなければ、redmine/tmpのパーミッションが強すぎだったり、666では起動する。または、/etc/apache2/.htaccessファイルがあっていないとか、、、
    2.git リポジトリーを立てる。

    このサイトが参考になります。
    概要:ここで作成したgitユーザがこのbase08ホストで、gitのリポジトリーを立てたり、アップデートしたりします。
    注意は説明で行われている、gitリポジトリーを使用するユーザ、gitユーザもbase08ホストで使用しますが、通常業務(趣味ではやらない)で使用するほうで、gitosisの設定を行います。
    下記ユーザのマシンでの設定
    #~/gitosis-admin/gitosis.conf
    [gitosis]

    [group gitosis-admin]
    writable = gitosis-admin
    members = aaa@TKNV bbb@bbc usr1@base08 root@base08

    [group dev-Ateam]
    writable = project1 project2 project-foo project-wow
    members = aaa@TKNV tuka@REP USER1@thinkpad-x300 usr1@base08 root@base08 git@base08

    # git@base08が今回の肝です。

    [repo project1]
    gitweb = yes
    owner = tknv@amateras
    description = module for UI and support Ajax

    大事なのはgit@base08
    アカウントをredmineで登録したいリポジトリーのグループに入れておくこと。
    あとは、リンクにあるように、/gitosis-admin/keydirに、git@base.pubのように、sshの公開鍵を入れて、gitでサーバにプッシュ。必要なユーザ分、全部おこなう。
    3.サーバ上でどうやって、gitリポジトリーを作成しpushのたびに更新するか。

    ここ参考になります。しかしながら、ネットにある大抵のHowToは簡単には最近、うまくゆかない。こちらのスキルレベルもあるが、こんだけユーザが多いと、ゴミ情報がたくさん、また、最近は新しいこうゆうテクノロジーが出てくると、とにかくやってみて(やればいいのだが、未検証もあり)サイトにアップする人が多く、間違えもそのままコピペしていたり、、、で
    #~/home/git/repositories//hooks/post-update
    export GIT_DIR=/home/git/checkout//.git

    pushd /home/git/checkout/ > /dev/null
    git reset --hard
    git pull
    popd > /dev/null

    WORKDIR="/home/git/checkout/"

    /usr/bin/git-update-server-info

    unset GIT_DIR

    で、先のサイトにもあるが、Don’t forget to create a _local git copy_ (via git clone git@localhost:.git in /home/git/checkout (or whatever folder you prefer)
    しかし、このままでも、まだ、無理で、もう2つやることが必要で、まずは、


    1.先の今回の肝、git@base08がこの、cloneした、ソースのユーザになっている必要がある。
    2.ssh-agentでこのgit@base08ユーザの秘密鍵の方を登録して、パスワード認証を無しにする必要がある。


    チェックリスト
    • git@~ ユーザがredmineでブラウジングしたいgitリポジトリーのアクセス許可グループに入っているか?(gitosis.conf)
    • git@~ ユーザのsshの秘密鍵がサーバ(redmineとgitリポジトリのある)にてssh-agentで追加され、パスワード認証が不要になっているか?
    • サーバ(redmineとgitリポジトリのある)の/home/git/checkout/のユーザがgit@~ であるか?

    勘違いでした。
    git clone で問題ない、、、

    How to create repo from remote(not at server)

    Tuesday, August 18, 2009

    Brew Tool Suite Perl API

    How to apply original keymap.ini

    オリジナルのキーマップ iniファイルを作成しテストケースを作るにあたって。

    use enumでハマリました。

    --keymap.ini

    [KEYMAP]
    AVK_SELECT=112
    AVK_UP=134
    AVK_DOWN=135
    AVK_LEFT=88
    AVK_RIGHT=89
    AVK_SOFT1=34
    AVK_SOFT2=35
    AVK_SOFT3=36
    AVK_SOFT4=36
    AVK_SEND=69
    AVK_CLR=70

    だとしたら、
    --Testcase.pl

    .....
    use enum qw( AVK_ASTERISK=1000 AVK_NUMBER_SIGN AVK_SELECT AVK_UP AVK_DOWN AVK_LEFT AVK_RIGHT AVK_SEND AVK_CLR AVK_END);
    .....

    のように、enumで定義するときに、順序を合わせないと想定通りの挙動をしなかった。

    iniファイルの内容をnameでマッピングするのかと思っていたのが間違え立った模様。
    足掛け、3日ハマリマシタ。Brewのデベロッパー(正式なアカウントがないと入れない)サイトでもぜんぜんこういう情報がなく。サイトも重いし。アカウント作成すれば入れるフォーラム(無料のサイト)でもあまり情報なしで、perl普段から使ってる人には常識なのかもしれないですが、、、

    慣れていないperlコードだけだと、自動テストをまとめてコントロールするのが大変なんで、rakeでできないかなーと模索中。
    Autoitも使用するので、rubyで全部コントロールできると楽。

    だれか、Brew Tool Suite Perl APIでなく、RubyにてBTILをSwigした、Brew Tool Suite知ってますか?
    Does anyone know Brew Tool Suite Ruby API that swiged BITL for ruby?

    Thursday, July 9, 2009

    Get BLogger Labels



    $label_url = "http://www.blogger.com/feeds/#{$userID}/blogs/#{$blogID}?alt=json-in-script&callback=listLabels"

    class BlogLabels

    def get_labels
    result = URLFetch.get($label_url)
    result_headless = result.gsub("listLabels(",'')
    pure_result = result_headless.gsub(");",'')
    JSON.parse(pure_result)['entry']['category']
    end

    end

    @labels = BlogLabels.new
    @labels.get_labels.each do |cont|
    puts cont['term']
    end

    JSON was not works.
    Change to use YAML.

    response = URLFetch.get($label_url)
    result = response.to_s
    result_headless = result.gsub("listLabels(",'')
    pure_result = result_headless.gsub(");",'')
    json_to_yaml = YAML::load(pure_result)['entry']['category']

    Monday, July 6, 2009

    iblogspot

    To watch blogspot site on iphone by Google App Engine.
    But I asked check it by iphone to co. person.
    He said

    "Slow and Why don't you use WordPress ?".


    sad...

    Thursday, June 18, 2009

    Don't forget regsvr32 AutoItX3.dll

    When using Watir,should register AutoItX3.dll

    >cd C:\ruby\lib\ruby\gems\1.8\gems\watir-1.5.6\watir\
    >regsvr32 AutoItX3.dll

    enjoy Watir!

    Tuesday, June 16, 2009

    run Jruby on Google App Engine from windows

    Basically follow this lecture OK.
    http://blog.bigcurl.de/2009/04/running-sinatra-apps-on-google.html
    jruby-rack
    Get a fresh version from http://github.com/nicksieger/jruby-rack/tree/master

    cd jruby-rack
    PATH-TO-JRUBY/bin/jruby -S rake SKIP_SPECS=true

    1.You should check directory.
    ex.)C:\jruby-rack
    should not path include "space" etc.
    I could not rake in Document~ directory.
    2.use Jruby from "git clone git://kenai.com/jruby~main"
    I stuck use other dist.

    that all,no problems
    p.s. better has Cygwin for use split-jruby.sh
    and when running on local by C:\appengine-java-sdk-1.2.0\bin\dev_appserver.cmd,error.
    But in Google App Engine,no error.
    this is my TODO:

    Wednesday, June 10, 2009

    How to down load file.


    #!/usr/bin/env ruby

    require 'test/unit'
    require 'rubygems'
    require 'watir'
    require 'win32ole'



    class FileUpLoadTest < Test::Unit::TestCase
    include Watir

    def test_fileup
    ie = Watir::IE.new
    ie.goto('foo.com/fileup.html')
    assert(ie.file_field(:name,"register_data").exists?,message="error none file field")

    #Start down load
    ie.file_field(:id,'register_data').click_no_wait
    # should click_no_wait,otherwise wait forever behind modal window.

    windwName_dwn = "ファイルのダウンロード"
    windwName_sve = "名前を付けて保存"
    autoit=WIN32OLE.new("AutoItX3.Control")
    autoit.WinWait(windwName_dwn)
    autoit.WinActivate(windwName_dwn)
    autoit.ControlClick(windwName_dwn,"","[CLASS:Button;INSTANCE:2]")
    pathAndName = "var/foo.txt"
    autoit.WinWait(windwName_sv)
    autoit.WinActivate(windwName_sv)
    autoit.ControlSetText(windwName_sv, "", 1148, "#{pathAndName}")
    autoit.ControlClick(windwName_sv,"","[CLASS:Button;INSTANCE:2]")
    autoit.WinWait("ダウンロードの完了")
    end
    end

    Tuesday, June 9, 2009

    How to file up load


    #!/usr/bin/env ruby

    require 'test/unit'
    require 'rubygems'
    require 'watir'
    require 'win32ole'



    class FileUpLoadTest < Test::Unit::TestCase
    include Watir

    def test_fileup
    ie = Watir::IE.new
    ie.goto('foo.com/fileup.html')
    assert(ie.file_field(:name,"register_data").exists?,message="error none file field")
    path = "C:\\InstantRails-2.0-win\\rails_apps\\somefile.csv" # set("#{path}")
    ie.file_field(:id,'register_data').click_no_wait
    # debug code check file path and sleep sec.
    puts "#{path}"
    puts Time.now
    sleep(5)
    puts Time.now
    # debug code end

    autoit=WIN32OLE.new("AutoItX3.Control")
    autoit.WinWait("ファイルの選択")
    autoit.WinActivate("ファイルの選択")
    autoit.ControlSetText("ファイルの選択", "", 1148, "#{path}")
    autoit.Send("{ENTER}")

    ie.button(:name,"btnSubmitFile").click
    wait_until {ie.text.include? "アップロードされました。"} #rendering待ち
    assert(ie.text.include?("アップロードされました。"),message="error import" ) #データインポートチェック

    ie.close

    end

    end