GANCHIKU.com

Testing_FITを使ってみる。

2007年6月20日
PHP

PEPrの投票フェーズにいて、前から気になっていたTesting_FITを使ってみたので、簡単に書いてみる。
FITとは、Framework for Integrated Testsの略で、顧客と開発者とで協力してテストをしていくための仕組みだ。。。と書いたところで、どう考えても私が説明するよりも、よっぽどわかりやすいサイトがあるので面倒になった。そちらを読まれたし。・IBM コード品質の追求: FITで解決する

私は、Testing_FITを使用して、それに関して書くだけ。そのネタとして上記のリンク先がわかりやすかったので、そのサンプルを元に簡単なプログラムを作成した。ついでなのでソースを全部載せてみよう。つーか、金額を表すのにfloat使うな、とツッコミを受けそう。。

今回私が使ったのは、Testing_FIT_Fixture_Column。HTMLのtableの行や列に変数やメソッドの結果を入れて、実際に正しかったかを見るプログラム。こんな感じでできる。→Example: Math(もし、配布しているサンプルのコードと同じだったらなんか突っ込みたくなるが、ここでは大事なネタでなさそうなので、放置。)

で、上の「IBM コード品質の追求: FITで解決する」のTrendIndicatorから作ってみよう。私のファイル構成はこんな感じ。TrendIndicatorクラスは面倒だったので、TrendIndicatorFITクラスにぶち込んでみる。本当は、どこからのモデルかユーティリティに入るのだろうが、気にしない。

+ working/
      + fixture/TrendIndicatorFIT.php
      + in/trendindicator.html
      + web.php

簡単に説明すると、TrendIndicatorFIT.phpは、テストの対象となるTrendIndicatorクラスとFITコードのTrendIndicatorFITクラスが入っている。trendindicator.htmlは、FITを使って作られた構造化モデルである。変数とそのメソッドの結果の一覧みたいなものだと考えれば良い。web.phpは、WEBからFITを実行するためのスクリプトである。では、trendindicator.htmlの中身を見てみる。

< !DOCTYPE html public "-//w3c//dtd html 4.0 transitional//en">


   
   

Trend Indicator

TrendIndicatorFIT
value1 value2 trend()
84.0 71.2 decreasing
67.6 89.0 increasing
50.0 50.0 constant
fit.Summary
This document implements an example from http://www-06.ibm.com/jp/developerworks/java/060317/j_j-cq02286.shtml

$value1、 $value2にそれぞれ、84.0、71.2を入れるとtrend()がdecreasingという文字列を返すなどのテストを三つ上げてある。つまり、$value1が$value2よりも大きければ、trend()が”increased”を返し、小さければ、”decreased”を返し、同じであれば、”constant”を返すという単純なものだ。これに基づいて書いたコードTrendIndicatorFIT.phpが次の通り。

< ?php
require_once 'Testing/FIT/Fixture/Column.php';
// テスト対象クラス
class TrendIndicator
{
    public static function determineTrend($value1, $value2) {
        $result = null;

        if (!(is_float($value1) and is_float($value2))) {
            throw new Exception("TrendIndicatorException");
        }

        if ($value1 > $value2) {
            $result = "decreasing";
        } else if ($value1 < $value2) {
            $result = "increasing";
        } else if ($value1 == $value2) {
            $result = "constant";
        }

        return $result;
    }
}

// FITクラス
class TrendIndicatorFIT extends Testing_FIT_Fixture_Column
{
    public $value1;
    public $value2;

    protected $_typeDictionary = array(
        'value1' => 'float',
        'value2' => 'float',
        'trend()' => 'string'
        );

    public function trend() {
        return TrendIndicator::determineTrend($this->value1, $this->value2);
    }
}
?>

$_typeDictionaryの動作は実は問題があるのだが、float, string, integerは動くようなので、ここでは、float, stringを使ってみた。これで完成。web.phpから見てみると、サンプルにあるようなテーブル形式にexpectedとactualとしてテストに合格したかどうかを表してくれる。実は、これPHPUnitでも書いてもいいのだけど、書く量が増えることと、プログラムのことを知らない顧客がわからないという点からFITというアプローチはどう?ってものだ。ちなみにweb.phpはこんな感じ。

< ?php
/**
 * start fut runner
 */

// tell where to find project fixtures
$fitDir =   dirname( __FILE__ ) . '/fixture';
define( 'TESTING_FIT_FIXTURE_DIR', $fitDir );

$baseDir = realpath( dirname( __FILE__ ) . '/../..' );
$incPath = get_include_path() . PATH_SEPARATOR  . realpath( $baseDir . '/..' );
set_include_path( $incPath );

$in = 'in/trendindicator.html';

include_once 'Testing/FIT/Runner.php';
$fr =   new Testing_FIT_Runner();
$fr->run( $in, '-' );
?>

しかし、これだけでは何がウレシイのかよくわからないので、もう少し長いプログラムを書いてみよう。これも、上記のサイトから。Javaで書いてあるものをPHPに移植してみることにする。仕様はこんなところらしい。

皆さんが、あるビール会社の注文処理システムを構築するように依頼されたと考えてみてください。このビール会社は様々なタイプの飲料を販売していますが、大きく分けると、季節商品(seasonal)と通年商品(year-round)、という2つのカテゴリーに分類することができます。このビール会社は卸売りとして操業しているため、すべての飲料はケース単位で販売されます。小売店への販売奨励策として、複数ケース買いに対する値引きサービスがあります。値引きの仕組みは、ケースの数と、季節商品か通年商品かによって変化します。

こうした要求の管理は、なかなか面倒です。例えば、ある小売店が季節商品を50ケース買う場合には値引きは適用されません。しかし、この50ケースが季節商品『ではない』場合には、12%の値引きが適用されます。ある小売店が季節商品を100ケース買う場合には、値引きは適用されますが、値引率は 5%だけです。季節商品ではない飲料を100ケース買う場合には、17%の値引きです。200ケース買う場合にも、似たルールがあります。

確かに面倒だ。数やその商品によって割引率が違うというのはよくあるが、テストが面倒そう。と、いったところで、FITの登場ですよ!上記の記事には、単体テストはJUnitでを使用し、ビジネス・ルールのテストや値の組み合わせに関わるテストにはFITを使用するのがいいのではないか、と書いてある。

そこで、記事に倣って、単体テストはPHPUnitで行い、値の組み合わせに関わるテストにはTesting_FITを使う。まずはファイル構成から。

+ working/
      + fixture/DiscountStructureFIT.php
      + unit/MoneyTest.php
      + unit/WholesaleOrderTest.php
      + in/discountstructure.html
      + web.php

DiscountStrucureFIT.phpは、面倒だったので、Moneyクラス、WholesaleOrderクラス、ProductTypeクラス、PricingEngineクラスといった本来はここに入ることはないクラスまで突っ込んである。そして、本来入るべきFITコードのDiscountStructureFITクラスも入っている。MoneyTest.phpとWholesaleOrderTest.phpは、それぞれMoneyクラスとWholesaleOrderクラスの単体テストコードが入っている。discountstructure.htmlは、FITを使って作られた構造化モデルである。web.phpは、先ほどと同じだけどもdiscountstructure.htmlを見るように変更しただけ。

< !DOCTYPE html public "-//w3c//dtd html 4.0 transitional//en">


   
   

Discount Structure

皆さんが、あるビール会社の注文処理システムを構築するように依頼されたと考えてみてください。このビール会社は様々なタイプの飲料を販売していますが、大きく分けると、季節商品(seasonal)と通年商品(year-round)、という1つのカテゴリーに分類することができます。このビール会社は卸売りとして操業しているため、すべての飲料はケース単位で販売されます。小売店への販売奨励策として、複数ケース買いに対する値引きサービスがあります。値引きの仕組みは、ケースの数と、季節商品か通年商品かによって変化します。 こうした要求の管理は、なかなか面倒です。例えば、ある小売店が季節商品を50ケース買う場合には値引きは適用されません。しかし、この50ケースが季節商品『ではない』場合には、12%の値引きが適用されます。ある小売店が季節商品を100ケース買う場合には、値引きは適用されますが、値引率は 5%だけです。季節商品ではない飲料を100ケース買う場合には、17%の値引きです。200ケース買う場合にも、似たルールがあります。 http://www-06.ibm.com/jp/developerworks/java/060317/j_j-cq02286.shtml
* 注意 10個でかつ、季節商品『ではない』場合には、5%の値引き適用されることは書いてないので、私が追加。 by shin
DiscountStructureFIT
listPricePerCase numberOfCases isSeasonal discountPrice() discountAmount()
10.00 10 true $100.00 $0.00
10.00 10 false $95.00 $5.00
10.00 50 true $500.00 $0.00
10.00 50 false $440.00 $60.00
10.00 100 true $950.00 $50.00
10.00 100 false $830.00 $170.00
10.00 200 true $1800.00 $200.00
10.00 200 false $1600.00 $400.00
fit.Summary
This document implements an example from http://www-06.ibm.com/jp/developerworks/java/060317/j_j-cq02286.shtml

「値段」や「季節ものかどうか」で組み合わせた8つのパターンでいくら値引きがあるかを想定しておく。
Moneyクラス、WholesaleOrderクラス、ProductTypeクラス、PricingEngineクラスも適当に実装してみる。そして、MoneyクラスとWholesaleOrderクラスはPHPUnitで書いてみる。MoneyTest.phpは以下の通り。

< ?php
require_once 'PHPUnit/Framework/TestSuite.php';
require_once 'PHPUnit/TextUI/TestRunner.php';

require_once '../fixture/DiscountStructure.php';

class MoneyTest  extends PHPUnit_Framework_TestCase
{

    public function testToString()
    {
        $money = new Money(10.00);
        $total = $money->mpy(10);
        $this->assertEquals("$100.00", $total->toString());
    }

    public function testEquals()
    {
        $money = Money::parse("$10.00");
        $total = new Money(10);
        $this->assertEquals($money, $total);
    }

    public function testMultiply()
    {
        $money = new Money(10.00);
        $total = $money->mpy(10);

        $discountAmount = $total->mpy(0.05);
        $this->assertEquals("$5.00", $discountAmount->toString());
    }

    public function testSubtract()
    {
        $money = new Money(10.00);
        $total = $money->mpy(10);
        $discountAmount = $total->mpy(0.05);
        $discountedPrice = $total->sub($discountAmount);

        $this->assertEquals("$95.00", $discountedPrice->toString());
    }

    public function testParse()
    {
        $money = Money::parse("$10.00");
        $this->assertEquals("$10.00", $money->toString());
    }
}
?>

WholesaleOrderTest.phpは次の通り

< ?php
require_once 'PHPUnit/Framework/TestSuite.php';
require_once 'PHPUnit/TextUI/TestRunner.php';

require_once '../fixture/DiscountStructure.php';

class WholesaleOrderTest  extends PHPUnit_Framework_TestCase
{
    public function testGetCalculatedPrice()
    {
        $order = new WholesaleOrder();
        $order->setDiscount(0.05);
        $order->setNumberOfCases(10);
        $order->setPricePerCase(new Money(10.00));
        $this->assertEquals("$95.00", $order->getCalculatedPrice()->toString());
    }

    public function testGetDiscountedDifference()
    {
        $order = new WholesaleOrder();
        $order->setDiscount(0.05);
        $order->setNumberOfCases(10);
        $order->setPricePerCase(new Money(10.00));

        $this->assertEquals("$5.00", $order->getDiscountedDifference()->toString());
    }
}
?>

私は、中途半端な仕様よりもテストの方が期待している動作がわかるので、テストの方がうれしかったりする。本当は、ユニットテストにはどんどんコメントを書いていくのがいいのだが、それも今回は割愛。。

そして、Moneyクラス、WholesaleOrderクラス、ProductTypeクラス、PricingEngineクラス、そして、DiscountStructureFITクラスまで一気にいく。つか、ベタって貼っただけ。。。はい。手抜きですいません。

< ?php
// Following site is used as reference
// http://www-06.ibm.com/jp/developerworks/java/060317/j_j-cq02286.shtml

require_once 'Testing/FIT/Fixture/Column.php';

// {{{ Money Class
class Money
{
    public $money;
    public function __construct($money = 0)
    {
        $this->money = floatval($money);
    }

    public function __toString()
    {
        return sprintf("$%.2f", $this->money);
    }

    // バージョンによって、echoとprintのときだけとか。なので、一応。
    public function toString()
    {
        return $this->__toString();
    }

    public static function parse($value)
    {
        return new Money(str_replace("$", "", $value));
    }

    public function mpy($value)
    {
        $result = null;
        // Moneyオブジェクトの場合
        if ($value instanceof Money) {
            $result = $this->money * $value->money;
        } else if(is_numeric($value)) {
            $result = $this->money * $value;
        } else {
            // TODO
        }
        return new Money($result);
    }

    public function sub($value)
    {
        $result = null;
        // Moneyオブジェクトの場合
        if ($value instanceof Money) {
            $result = $this->money - $value->money;
        } else if(is_numeric($value)) {
            $reslut = $this->money - $value;
        } else {
            // TODO
        }
        return new Money($result);
    }
}
// }}}

// {{{ WholesaleOrder Class
class WholesaleOrder
{
    private $numberOfCases;
    private $productType;
    private $pricePerCase;
    private $discount;

    public function getDiscount()
    {
        return floatval($this->discount);
    }

    public function setDiscount($discount)
    {
        $this->discount = floatval($discount);
    }

    public function getCalculatedPrice()
    {
        $money = new Money($this->pricePerCase);
        $totalPrice = $money->mpy($this->numberOfCases);
//        $totalPrice = $this->pricePerCase->mpy($this->numberOfCases);
        $tmpPrice = $totalPrice->mpy($this->discount);
        return $totalPrice->sub($tmpPrice);
    }

    public function getDiscountedDifference()
    {
        $money = new Money($this->pricePerCase);
        $totalPrice = $money->mpy($this->numberOfCases);
//        $totalPrice = $this->pricePerCase->mpy($this->numberOfCases);
        return $totalPrice->sub($this->getCalculatedPrice());
    }

    public function getNumberOfCases()
    {
        return $this->numberOfCases;
    }

    public function setNumberOfCases($numberOfCases)
    {
        $this->numberOfCases = $numberOfCases;
    }

    public function setPricePerCase($pricePerCase)
    {
        $this->pricePerCase = $pricePerCase;
    }

    public function getPricePerCase()
    {
        return $this->pricePerCase;
    }

    public function setProductType($productType)
    {
        $this->productType = $productType;
    }

    public function getProductType()
    {
        return $this->productType;
    }
}
// }}}

// {{{ ProductType
class ProductType
{
    const SEASONAL = "0";
    const YEAR_ROUND = "1";
}

// }}}

// {{{ PricingEngine Class
class PricingEngine
{
    // ルールは省略
    public static function applyDiscount($order)
    {
        $discount = 0;
        if ($order->getNumberOfCases() < = 10) {
            if ($order->getProductType() === ProductType::YEAR_ROUND) {
                $discount = 0.05;
            }
        } else if ($order->getNumberOfCases() < = 50) {
            if ($order->getProductType() === ProductType::YEAR_ROUND) {
                $discount = 0.12;
            }
        } else if ($order->getNumberOfCases() < = 100) {
            if ($order->getProductType() === ProductType::YEAR_ROUND) {
                $discount = 0.17;
            } else {
                $discount = 0.05;
            }
        } else if ($order->getNumberOfCases() < = 200) {
            if ($order->getProductType() === ProductType::YEAR_ROUND) {
                $discount = 0.20;
            } else {
                $discount = 0.10;
            }
        }
        $order->setDiscount($discount);
    }
}
// }}}

// {{{ DiscountStructureFIT
class DiscountStructureFIT extends Testing_FIT_Fixture_Column
{
    public $listPricePerCase;
    public $numberOfCases;
    public $isSeasonal;

    protected $_typeDictionary = array(
        'listPricePerCase' => 'float',
        'numberOfCases' => 'integer',
//        'isSeasonal' => 'boolean', // XXX boolean is NOT IMPLEMENTED
        'isSeasonal' => 'string',
        'discountPrice()' => 'float',
        'discountAmount()' => 'float'
    );

    public function discountPrice()
    {
        $order = $this->doOrderCalculation();
        return $order->getCalculatedPrice()->toString();
    }

    public function discountAmount()
    {
        $order = $this->doOrderCalculation();
        return $order->getDiscountedDifference()->toString();
    }

    public function parse($value)
    {
        return Money::parse($value);
    }

    private function doOrderCalculation()
    {
        $order = new WholesaleOrder();
        $order->setNumberOfCases($this->numberOfCases);
        $order->setPricePerCase($this->listPricePerCase);

        if ($this->isSeasonal === 'true') {
            $order->setProductType(ProductType::SEASONAL);
        } else {
            $order->setProductType(ProductType::YEAR_ROUND);
        }

        PricingEngine::applyDiscount($order);
        return $order;
    }
}

//}}}
?>

ビジネスロジックのPricingEngineのapplyDiscountは、そのままゴリゴリ書いちゃった。また、無理矢理テストが通るように作成してあるので、ツッコミどころ満載なのだが、使って気になるところがいくつか。

  • 現状では、FixtureのTypeにクラスを指定することができない。booleanも指定することができない。stringとintegerとfloatのみ。おそらく将来的にはその辺を対応していないときつそうだ。今回参考にしたIBMの記事で使用しているJavaでは、その辺対応しているようだ。さすが、Java。カタイね。
  • $_typeDictionaryは、冗長な気がする。まぁ、しゃーないんだろうけど。。
  • __toStringがechoもしくは、printのとき以外は、stringで認識してくれないので、自作のtoStringを作成。噂では、5.2.1から認識するとか? って、Testing_FITとは全く関係ないがw
  • 実際にMS WordやらMS Excelからインポートしたわけではないからなんとも言えないが、顧客とテストを協力して行うといっても、顧客に教育する必要がありで、ちゃんとその辺をわかってくれる顧客でないと無理かなー、と。

長々と、ソースを貼り付けただけの記事だったが、こんだけ調べた結果気に入ったので、投票しておいた。 今日が〆切だったのね。無事に通ったようで何より。

しかし、久しぶりにPHPを書いてみたら、変数の書き方とか忘れてしまっていた。。。型を宣言したり、$を書かなかったりと、最初は戸惑ったけど、少し感覚が戻ってきた気がする。

コメントをどうぞ

メールアドレスが公開されることはありません。 * が付いている欄は必須項目です

*

次のHTML タグと属性が使えます: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Shin Ohno 2003-2012