LoginSignup
3

More than 5 years have passed since last update.

pyramidのadd_request_methodで付加した属性のテストの仕方

Last updated at Posted at 2014-05-03

pyramidのadd_request_method

pyramidのadd_request_methodというディレクティブでrequestが持つpropertyを付加することができる。
(過去にはadd_request_propertyというディレクティブも存在したが速攻でdeprecatedになった)

add_request_methodの効果

document: http://docs.pylonsproject.org/projects/pyramid/en/latest/api/config.html#pyramid.config.Configurator.add_request_method

オプションについては以下2つを覚えておくと良い

  • reify -- requestに属性を付加する。付加した属性はキャッシュされる
  • property -- requestに属性を付加する。付加した属性は都度計算される

何も付けなければmethodとして付加される。(またreify=Trueならば自動的にpropertyとして付加される)

## configuration
def includeme(config):
    ## request.get_foo()として呼べる
    config.add_request_method(get_foo, "get_foo")

    ## request.fooとしてアクセスできる
    config.add_request_method(get_foo2, "foo", reify=True)
    config.add_request_method(get_foo2, "foo", property=True)

add_request_methodで付加した属性のテスト

テスト。unit testならテキトウにmockを使ったり。dummyを使ったりでどうにかなる。
integration testの際にどうすれば良いかという話。

add_request_methodで定義されたディレクティブが有効になるところ。

pyramidのコード見よう。pyramid/router.pyに答えが書いてある。
すごくざっくり言うと以下のことが分かる。

  • add_request_methodはIRequestExtensionsというinterfaceをkeyに格納される
  • pyramid.request.Request._set_extensions()で設定される

テストの書き方の1例

以上を参考にintegration testの書き方の例
今回はrequest.fooを設定する。request.fooで取得できるか確認するだけ。

# -*- coding:utf-8 -*-
import unittest


## definition

foo = object()

def get_foo(request):
    return foo

def includeme(config):
    config.add_request_method(get_foo, "foo", reify=True)


## test

class Tests(unittest.TestCase):
    def _makeOne(self, config, path="/"):
        from pyramid.request import Request
        from pyramid.interfaces import IRequestExtensions

        request = Request.blank(path)
        extensions = config.registry.getUtility(IRequestExtensions)
        request.registry = config.registry
        request._set_extensions(extensions)
        return request

    def test_it(self):
        from pyramid.testing import testConfig

        with testConfig() as config:
            config.include(includeme)

            ### request time
            request = self._makeOne(config, path="/")
            self.assertEqual(request.foo, foo)

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
3