Kotlin + Koinでテストコードを書いてみた
はじめに
ユニットテストの自動化はやった方が良いぞと分かっていても、Androidのコーディングに全然慣れていなかったので手がつかなかった。
プログラミング言語のメージャーバージョンの更新(JavaやらSwift)、ライブラリの更新などで、自分の将来の手間を減らすためにも、ユニットテストの自動化を必要性を感じたので、Androidでのテストの方法を調べてみた。
参考サイト
環境
環境はKotlinと、DIコンテナとしてKoinを使用
SpringBootの影響か、DIコンテナを使わないとテストが書けない身体に・・・(そもそも、DIコンテナ使う前はテスト書いてない)
自分の能力では、DIコンテナを利用しないとモックが作りづらい・・・
Kotlinで使用できるDIコンテナは幾つかあるけど、個人的にKoinが学習コストが低そうだった
(JavaではDagger2を使ってたけど、試しにKotlin + Daggar2のコードを書こうとして、面倒臭くなって諦めた)
- Android Studio 3.4
- Kotlin 1.3.30
- Koin 1.0.2
ライブラリの準備
Koinのライブラリを追加するために、Gradleを修正する
dependencies { ...(中略) // Koin for Android implementation 'org.koin:koin-android:1.0.2' implementation 'org.koin:koin-test:1.0.2' }
実装部分の作成
まず、現在時刻を取得するための処理を作る
まずはインターフェースを定義
interface ISystemClock { fun currentDateTime(): Calendar }
「ISystemClock」を実装するクラスを定義する
class SystemClock: ISystemClock { override fun currentDateTime(): Calendar { return Calendar.getInstance() } }
次に、適当な文字列+時刻の文字列を返す処理を作る
インターフェースを定義
interface IMessenger { fun getMessage(): String }
実装を定義
class Messenger( private val iSystemClock: ISystemClock ) : IMessenger { override fun getMessage(): String { val formatter = SimpleDateFormat("yyyy年MM月dd日 HH時mm分ss秒", Locale.US) val dateString = formatter.format(this.iSystemClock.currentDateTime().time) return "Hello world!!! ${dateString}" } }
実装は「Hello world!!!」に現在時刻を付け足した文字列を返すだけ
現在時刻の取得は、先に定義したISystemClockの実装から取得するようにしている
テストコードの作成
作成したMessengerの実装が正しく動作するか確認するためのテストを作成する
とりあえず単純なテストを作成してみるが、getMessageメソッドで現在時刻を取得するので失敗する
class MessengerTest { private val messenger = Messenger(SystemClock()) @Test fun getMessage() { Assert.assertEquals("Hello world!!! 2019年04月01日 10時18分52秒", messenger.getMessage()) } }
なので、ISystemClockを実装して決まった時間を返すモッククラスを作成する
class MockSystemClock: ISystemClock { override fun currentDateTime(): Calendar { val calendar = Calendar.getInstance() calendar.set(2019, Calendar.APRIL, 1, 10, 18, 52) return calendar } }
そしてテスト時に、モッククラスのインスタンスを使用するように、koinで依存性を定義する
依存性の定義は、適当な場所に「DIModules.kt」というファイルを作成して以下のように記述した
val mockModule: Module = module { single { MockSystemClock() as ISystemClock } single { Messenger(get()) as IMessenger } }
依存性を定義したので、テストも定義したものを使用できるように修正する
class MessengerTest: AutoCloseKoinTest() { private val iMessenger by inject<IMessenger>() @Before fun before() { startKoin(listOf(mockModule)) } @Test fun getMessage() { Assert.assertEquals("Hello world!!! 2019年04月01日 10時18分52秒", iMessenger.getMessage()) } }
おわりに
Androidアプリに限らず、DIの考え方を利用すると色々な挙動のモックを定義できるので、ユニットテストが作りやすい
iOSの方のテストの自動化についても調べようと思う
負荷テストで使うJmeterのパラメータを決めやすくする
はじめに
とあるサービスをクラウド上に公開することになった。
負荷テストをやって、ボトルネックの特定、現状対応できる利用者の数、将来の利用者数に合わせたスケールアップのタイミングを調べるため、Jmeterで負荷テストをすることにした。
色んなサイトや本を見て、Jmeterを使った負荷テストは分かってきた・・・気がする
しかし、やっているうちに、負荷の掛け方がイマイチのように思えた
よく変える設定値は「スレッド数」と「ループ回数」のみで、これだけだとボトルネックは分かっても、どこまでスループットが出ているか・レスポンスが急激に遅くなるタイミングが自分にはよく分からなかった
(自分のJmeterの使い方・結果の見方が悪いのかもしれない)
Jmeterのパラメータの決め方について色々調べてみると、わかりやすいサイトがあった
参考サイト
Jmeterに「定数スループットタイマ」というものがある、ということをこのサイトを見るまで知らなかった・・・
パラメータを算出するスクリプトはコチラ↓
スクリプトは以下のパラメータを与えてあげると、「スレッド数」と「ループ回数」と「定数スループットタイマ」を算出
今までは「スレッド数」と「ループ回数」を悩みながら決めていたけど、上記のパラメータの方が決めやすい!
自分は、Jmeterの設定をWindowsで設定し、sshでクラウド上のLinuxに転送し、LinuxでJmeterをコマンド実行するようにしている
なので、C#版を作った
見た目
<Window x:Class="JmeterParam.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:local="clr-namespace:JmeterParam" mc:Ignorable="d" Title="MainWindow" Height="450" Width="552.119"> <Grid> <Grid.ColumnDefinitions> <ColumnDefinition/> <ColumnDefinition/> </Grid.ColumnDefinitions> <Grid.RowDefinitions> <RowDefinition/> <RowDefinition/> <RowDefinition/> <RowDefinition/> <RowDefinition/> <RowDefinition/> <RowDefinition/> <RowDefinition/> <RowDefinition/> <RowDefinition/> <RowDefinition/> </Grid.RowDefinitions> <Label Content="リクエスト送信に使用するサーバ台数:" HorizontalAlignment="Right" VerticalAlignment="Center" Grid.Column="0" Grid.Row="0"/> <TextBox HorizontalAlignment="Left" Text="{Binding ServerCount}" Height="23" TextWrapping="Wrap" VerticalAlignment="Center" Width="70" Grid.Column="1" Grid.Row="0" TextAlignment="Right" PreviewTextInput="TextBox_PreviewTextInput"/> <Label Content="想定スループット:" HorizontalAlignment="Right" VerticalAlignment="Center" Grid.Column="0" Grid.Row="1"/> <TextBox HorizontalAlignment="Left" Text="{Binding AssumedThroughput}" Height="23" TextWrapping="Wrap" VerticalAlignment="Center" Width="70" Grid.Column="1" Grid.Row="1" TextAlignment="Right" PreviewTextInput="TextBox_PreviewTextInput"/> <Label Content="1スレッドグループに含まれるリクエスト数:" HorizontalAlignment="Right" VerticalAlignment="Center" Grid.Column="0" Grid.Row="2"/> <TextBox HorizontalAlignment="Left" Text="{Binding RequestCountByThreadGroup}" Height="23" TextWrapping="Wrap" VerticalAlignment="Center" Width="70" Grid.Column="1" Grid.Row="2" TextAlignment="Right" PreviewTextInput="TextBox_PreviewTextInput"/> <Label Content="試験実施時間:" HorizontalAlignment="Right" VerticalAlignment="Center" Grid.Column="0" Grid.Row="3"/> <TextBox HorizontalAlignment="Left" Text="{Binding StressPeriod}" Height="23" TextWrapping="Wrap" VerticalAlignment="Center" Width="70" Grid.Column="1" Grid.Row="3" TextAlignment="Right" PreviewTextInput="TextBox_PreviewTextInput"/> <Label Content="想定リクエスト処理時間:" HorizontalAlignment="Right" VerticalAlignment="Center" Grid.Column="0" Grid.Row="4"/> <TextBox HorizontalAlignment="Left" Text="{Binding AssumedResponceTime}" Height="23" TextWrapping="Wrap" VerticalAlignment="Center" Width="70" Grid.Column="1" Grid.Row="4" TextAlignment="Right" PreviewTextInput="TextBox_PreviewTextInput"/> <Button x:Name="CalcButton" Grid.Column="0" Grid.ColumnSpan="2" Grid.Row="5" Content="計算" Margin="10,5" Click="CalcButton_Click"/> <Label Content="スレッド数:" HorizontalAlignment="Right" VerticalAlignment="Center" Grid.Column="0" Grid.Row="7"/> <TextBox HorizontalAlignment="Left" Height="23" Text="{Binding ThreadCount}" TextWrapping="Wrap" VerticalAlignment="Center" Width="70" Grid.Column="1" Grid.Row="7" IsReadOnly="True" TextAlignment="Right"/> <Label Content="ループ回数:" HorizontalAlignment="Right" VerticalAlignment="Center" Grid.Column="0" Grid.Row="8"/> <TextBox HorizontalAlignment="Left" Height="23" Text="{Binding LoopCount}" TextWrapping="Wrap" VerticalAlignment="Center" Width="70" Grid.Column="1" Grid.Row="8" IsReadOnly="True" TextAlignment="Right"/> <Label Content="定数スループットタイマー:" HorizontalAlignment="Right" VerticalAlignment="Center" Grid.Column="0" Grid.Row="9"/> <TextBox HorizontalAlignment="Left" Height="23" Text="{Binding ConstantThroughputTimer}" TextWrapping="Wrap" VerticalAlignment="Center" Width="70" Grid.Column="1" Grid.Row="9" IsReadOnly="True" TextAlignment="Right"/> <Label Content="総アクセス数:" HorizontalAlignment="Right" VerticalAlignment="Center" Grid.Column="0" Grid.Row="10"/> <TextBox HorizontalAlignment="Left" Height="23" Text="{Binding AllAccessCount}" TextWrapping="Wrap" VerticalAlignment="Center" Width="70" Grid.Column="1" Grid.Row="10" IsReadOnly="True" TextAlignment="Right"/> </Grid> </Window>
/// <summary> /// MainWindow.xaml の相互作用ロジック /// </summary> public partial class MainWindow : Window { private class ViewModel: INotifyPropertyChanged { private int serverCount; private int assumedThroughput; private int requestCountByThreadGroup; private int stressPeriod; private double assumedResponceTime; private int threadCount; private int loopCount; private int constantThroughputTimer; private int allAccessCount; public int ServerCount { get { return this.serverCount; } set { this.serverCount = value; this.PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("ServerCount")); } } public int AssumedThroughput { get { return this.assumedThroughput; } set { this.assumedThroughput = value; this.PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("AssumedThroughput")); } } public int RequestCountByThreadGroup { get { return this.requestCountByThreadGroup; } set { this.requestCountByThreadGroup = value; this.PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("RequestCountByThreadGroup")); } } public int StressPeriod { get { return this.stressPeriod; } set { this.stressPeriod = value; this.PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("StressPeriod")); } } public double AssumedResponceTime { get { return this.assumedResponceTime; } set { this.assumedResponceTime = value; this.PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("AssumedResponceTime")); } } public int ThreadCount { get { return this.threadCount; } set { this.threadCount = value; this.PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("ThreadCount")); } } public int LoopCount { get { return this.loopCount; } set { this.loopCount = value; this.PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("LoopCount")); } } public int ConstantThroughputTimer { get { return this.constantThroughputTimer; } set { this.constantThroughputTimer = value; this.PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("ConstantThroughputTimer")); } } public int AllAccessCount { get { return this.allAccessCount; } set { this.allAccessCount = value; this.PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("AllAccessCount")); } } public event PropertyChangedEventHandler PropertyChanged; public void UpdateAllAccessCount() { this.allAccessCount = this.ThreadCount * this.RequestCountByThreadGroup * this.LoopCount * this.ServerCount; this.PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("AllAccessCount")); } } public MainWindow() { this.InitializeComponent(); this.WindowStartupLocation = WindowStartupLocation.CenterScreen; this.WindowStyle = WindowStyle.ToolWindow; this.DataContext = this.model; this.model.AssumedResponceTime = 1.5; } private ViewModel model = new ViewModel(); private void CalcButton_Click(object sender, RoutedEventArgs e) { if (this.model.ServerCount <= 0) { MessageBox.Show(this, "サーバ台数は 0 以上"); return; } if (this.model.AssumedResponceTime <= 0) { MessageBox.Show(this, "想定リクエスト処理時間は 0 以上"); return; } if (this.model.RequestCountByThreadGroup <= 0) { MessageBox.Show(this, "リクエスト数は 0 以上"); return; } this.model.ThreadCount = (int)Math.Ceiling(this.model.AssumedThroughput / this.model.ServerCount * this.model.AssumedResponceTime); this.model.LoopCount = (int)Math.Ceiling(this.model.StressPeriod / this.model.AssumedResponceTime / this.model.RequestCountByThreadGroup); this.model.ConstantThroughputTimer = (int)Math.Ceiling(60.0 / this.model.AssumedResponceTime * this.model.ThreadCount); this.model.UpdateAllAccessCount(); } private void TextBox_PreviewTextInput(object sender, TextCompositionEventArgs e) { Regex regex = new Regex("[0-9\\.]+"); e.Handled = !regex.IsMatch(e.Text); } }
アプリの見た目はこんな感じ
おわりに
このパラメータの決め方を使うことで、思った通りの負荷を掛けやすくなった。
負荷がわかりやすくなったので、どのスループット辺りから、WebサーバのCPUパワーが足りなくなりそうかも分かりやすくなった。
Python+Scrapyでスクレイピングした結果をDB(PostgreSQL)に保存する
はじめに
前に、Scrapyでクローニング・スクレイピングするスクリプトを作成した。
このときは、とあるディレクトリにスクレイピングした結果をjsonにして出力した。
↓そのときの話
そして、出力したjsonを別のスクリプトでDBに保存しようかと考えていた。
前回全く使用していなかった「pipelines.py」に処理を追加すると、DBに追加出来ることがわかったので、処理を追加してみた。
目次
参考サイト
環境
- PostgreSQL 11
- Python 3.6.8
- Scrapy 1.5.1
- psycopg2
- Scrapyで作成したプロジェクト名:MachiMachi
DBのテーブル作成
スクレイピングした結果を保存するテーブルを作成する。
今回は、以下のデータを登録するようにした。
- URL【主キー】
- ドメイン
- 登録日時
- タイトル
- コンテンツ(本文)
SQLはこんな感じ
-- コンテンツ create table contents ( url text not null , domain_name text not null , register_date timestamp with time zone not null , title text not null , contents text not null , constraint contents_PKC primary key (url) ) ; comment on table contents is 'コンテンツ'; comment on column contents.url is 'URL'; comment on column contents.domain_name is 'ドメイン'; comment on column contents.register_date is '登録日時'; comment on column contents.title is 'タイトル'; comment on column contents.contents is 'コンテンツ';
スパイダーの作成
今回も前回と同様に、「ライフハッカー(日本語版)」と「TechCrunch(日本語版)」をクローニングする。
前に作成したスパイダーと全く同じものを使うので、今回は省略。
DB接続用の設定ファイルを作成
Scrapyで作成したプロジェクトディレクトリにDB接続用の設定ファイル「setting.ini」を作成し、pipelineクラスから使用するようにした
[default] host=192.168.xx.xx port=5432 dbname=xxxxxxx user=xxxxxxx password=xxxxxxx
パイプの作成
Scrapyのドキュメントを参考に、スクレイピングした結果をDBにインサートする処理を作成
URLを主キーにしているので、既に同じURLが存在している場合は、インサートしないようにしている。
from configparser import ConfigParser import logging import psycopg2 import datetime class MachimachiPipeline(object): def __init__(self): self.connection = None self.cursor = None self.register_datetime = datetime.datetime.now() def open_spider(self, spider): """ スパイダーが実行されたときに呼ばれる :param spider:実行中のスパイダー """ config = ConfigParser() config.read('setting.ini') host = config.get('default', 'host') port = config.get('default', 'port') db_name = config.get('default', 'dbname') user = config.get('default', 'user') password = config.get('default', 'password') logging.info('connecting to db.') self.connection = psycopg2.connect('host=%s port=%s dbname=%s user=%s password=%s' % (host, port, db_name, user, password)) self.connection.autocommit = False self.cursor = self.connection.cursor() logging.info('connected to db.') def close_spider(self, spider): """ スパイダーの処理が終わるときに呼ばれる :param spider:処理中のスパイダー """ self.connection.commit() self.cursor.close() self.connection.close() logging.info('close connection to db.') def process_item(self, item, spider): """ スクレイピングされた項目毎に呼ばれる :param item:スクレイピングで取得したデータ :param spider:処理中のスパイダー :return:dictデータ """ url = item['url'] self.cursor.execute('SELECT * FROM contents WHERE (url = %s)', (url,)) record = self.cursor.fetchone() if record is not None: logging.info('url is already registered. url:%s' % (url,)) return item else: values = ( item['url'], spider.allowed_domains[0], self.register_datetime, item['title'], item['body'] ) self.cursor.execute('INSERT INTO contents (url, domain_name, register_date , title, contents)' ' VALUES (%s, %s, %s, %s, %s)', values) logging.info('contents is registered!!. url:%s' % (url,)) return item
設定の変更
Scrapyの設定も変更する。
「settings.py」の中に、パイプラインの設定がコメントアウトされているので、そのコメントアウトを解除する。
# Configure item pipelines # See https://doc.scrapy.org/en/latest/topics/item-pipeline.html ITEM_PIPELINES = { 'MachiMachi.pipelines.MachimachiPipeline': 300, }
クローニングの実行
全スパイダーのクローニングを実行するスクリプトを作成する(前に作成したものを一部修正しただけ)
修正点としては、DBに保存するのでファイル出力をしないようにした。
import subprocess import multiprocessing def get_crawler_list(): process = subprocess.Popen('scrapy list', shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) stdout_data, stderr_data = process.communicate() if process.returncode == 0: strings = stdout_data.decode('utf-8').split('\n') return list(filter(None, strings)) else: raise RuntimeError() def execute_scraping(crawler_name): cmd = 'scrapy crawl %s --loglevel=INFO' % (crawler_name,) subprocess.call(cmd.split()) def main(): jobs = [] for crawler_name in get_crawler_list(): job = multiprocessing.Process(target=execute_scraping, args=(crawler_name,)) jobs.append(job) job.start() [job.join() for job in jobs] print('finish !!!!') if __name__ == '__main__': main()
実行結果
クローニングを実行すると、PostgreSQLのテーブルに、以下のようにデータが保存された。(見やすくするため、ドメインとタイトルのみ表示)
select domain_name, title from contents;
domain_name | title -------------------+------------------------------------------------------------------------------------------------------------- www.lifehacker.jp | 孫の世話をする祖父母は長生きする:調査結果 jp.techcrunch.com | Amazonが家庭用メッシュルーターのEeroを買収してEcho製品拡販のベースに jp.techcrunch.com | ジェフ・ベゾスのメッセージ暴露、サウジが関与を否定 jp.techcrunch.com | 米国のiPhoneユーザーが昨年アプリに使った金額は平均79ドル、前年比36%アップ jp.techcrunch.com | GoogleドキュメントのAPIでタスクの自動化が可能に jp.techcrunch.com | 無登録物件のリスト掲載でパリ市がAirbnbを告訴 jp.techcrunch.com | 小売・飲食企業のアプリ開発支援を手がけるエンターモーションが2億円調達 jp.techcrunch.com | ソフトバンク、自動運転配達のnuroに9.4億ドルを資金提供 www.lifehacker.jp | 合体と分離ができる3in1トラベルバッグ「JW Weekender」を使ってみた www.lifehacker.jp | そこまでの生産性、本当に必要ですか? www.lifehacker.jp | キッチンに貼るだけで鍋蓋もまな板もスッキリ収納。菜箸置きにも使えそう〜 www.lifehacker.jp | 「この1本」で仕事はもっと上手くいく。ビジネスコーチに教わる缶コーヒー活用術 www.lifehacker.jp | オフィスとジムで兼用できる! どんなシーンでも履ける万能シューズがコール ハーンから登場 www.lifehacker.jp | 贈った方も得をする! コスパ抜群な「バレンタインギフト」を選ぶコツとは? www.lifehacker.jp | 元Google人材育成統括部長からのメッセージ「もうがんばらないでください」 www.lifehacker.jp | 子どもに初めてのスマホ、何に注意すべき? 「2019年度版チェックリスト」 www.lifehacker.jp | 世界的メール配信サービス会社メールチンプのCEO、ベン・チェストナットさんの仕事術 www.lifehacker.jp | 働き方を変えるには「短パン」から? 全員「複業」スタートアップCEOの仕事術 www.lifehacker.jp | オフシーズンの劇場をレンタルスペース化。アーティスティック・ディレクター、エイドリアンさんの仕事術 www.lifehacker.jp | 親が子どもに言ってはいけない8つの言葉とは? www.lifehacker.jp | 自分が「敏感すぎる」「繊細すぎる」人かどうかを測る「HSPセルフチェック」
おわりに
パイプラインを使い、DBに登録する処理ができた。
ドキュメントには、パイプラインの使用用途として、以下を例に挙げていた
- HTMLのクレンジング
- データのバリデーション
- 重複データの削除
- データベースへの保存
Scrapyでクローニング・スクレイピングした結果を、他のモジュールで加工・解析・保存をやろうと考えていたけど、パイプラインの組み合わせだけで、テキストマイニングまで出来そう。