LoginSignup
1
1

More than 5 years have passed since last update.

mox generator とか欲しい

Posted at

最近、テストを書くのがとても面倒になってきたので、mox で簡単にスタブできないか考えてみた。

まずは、クラスを。

mox_generator.py
import mox
class MoxGenerator(object):

    def __init__(self):
        self.mox = mox.Mox()

まだ思いつきの書き始めなので、とりあえず1つ書いてみました。なんでもいいから、True を返すスタブします。引数すら考慮せず。これはひどい(汗)。

mox_generator.py
    def true_stub(self, stub_class, stub_method, num_args):
        self.mox.StubOutWithMock(stub_class, stub_method)
        stubbed = getattr(stub_class, stub_method)
        args = tuple([mox.IgnoreArg() for i in range(num_args)])
        stubbed(*args).AndReturn(True)

呼び出すときは、こんな感じで。ここでは、MyClass.hoge(x,x,x) が True を返すように。最後の数字は、MyClass.hoge に渡す引数の個数です。

example_test.py
    moxgen= MoxGenerator()
    moxgen.true_stub(MyClass, 'hoge', 3)

もちろん Replay も面倒なので、名前が変だけどジェネレータに入れてしまえ!

mox_generator.py
    import contextlib
    @contextlib.contextmanager
    def mox_replay(self):
        self.mox.ReplayAll()
        yield
        self.mox.VerifyAll()

テスト実行側。

example_test.py
    with moxgen.mox_replay():
        MyClass.method_which_should_call_hoge()

github にも上げてみました。https://github.com/norobust/mox_generator なぜか本名でコミットされとるやないかー。どうやってユーザ名に変えるんだろう?

1
1
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
1
1