如何在 python 的金字塔框架中设置 request.authenticated_userid 的值

How can I set the value for request.authenticated_userid in pyramid framework of python

当我尝试将 authenticated_userid 的属性设置为请求参数时出现错误。它实际上是我用来模拟请求并查看响应的鼻子测试。

Traceback (most recent call last):
  File "/web/core/pulse/wapi/tests/testWapiUtilities_integration.py", line 652, in setUp
    setattr(self.request, 'authenticated_userid', self.data['user'].id)
AttributeError: can't set attribute

代码如下

@attr(can_split=False)
class logSuspiciousRequestAndRaiseHTTPError(IntegrationTestCase):
    def setUp(self):
        super(logSuspiciousRequestAndRaiseHTTPError, self).setUp()
        from pyramid.request import Request
        from pyramid.threadlocal import get_current_registry
        request = Request({
            'SERVER_PROTOCOL': 'testprotocol',
            'SERVER_NAME': 'test server name',
            'SERVER_PORT': '80',
        })
        request.context = TestContext()
        request.root = request.context
        request.subpath = ['path']
        request.traversed = ['traversed']
        request.view_name = 'test view name'
        request.path_info = 'test info'
        request.scheme = 'https'
        request.host = 'test.com'
        request.registry = get_current_registry()
        self.request = request
        self.data = {}
        self.createDefaultData()
        self.request.userAccount = self.data['user'].userAccount

    # @unittest.skip('Pre-Demo skip. Need to mock userAccountModel')
    @mock.patch('pulse.wapi.wapiUtilities.pyramid.threadlocal.get_current_request')
    @mock.patch('pulse.wapi.wapiUtilities.securityLog')
    def testHasRequest_raises400AndLogsError(
            self, securityLog, get_current_request):
        # Arrange
        get_current_request.return_value = self.request

        with self.assertRaises(exception.HTTPBadRequest):
            from pulse.wapi.wapiUtilities import logSuspiciousRequestAndRaiseHTTPError
            logSuspiciousRequestAndRaiseHTTPError()
            self.assertTrue(securityLog.called)
            self.assertTrue(securityLog.return_value.info.called)

我正在创建一个虚拟请求并向请求添加属性。

当调用此方法 logSuspiciousRequestAndRaiseHTTPError() 时,请求将通过获取用户帐户的方法进行解析。

userAccountID=authenticated_userid(self.request)

这 returns None 因为请求没有属性 self.request.authenticated_userid

如果您需要任何其他信息,请告诉我。

authenticated_userid是认证框架设置的具体化属性。

参见Logins with authentication for basic information

请提供更多代码,说明您如何设置请求,因为在目前的形式中,问题没有提供准确答案的详细信息。

终于找到解决办法了

我加了self.config = testing.setUp()

self.config.testing_securitypolicy(
    userid=self.data['user'].userAccount.id, permissive=True
)

添加了 userAccountId 作为测试安全策略的模拟值。

@attr(can_split=False)
class logSuspiciousRequestAndRaiseHTTPError(IntegrationTestCase):
    def setUp(self):
        super(logSuspiciousRequestAndRaiseHTTPError, self).setUp()
        from pyramid.request import Request
        from pyramid.threadlocal import get_current_registry
        self.config = testing.setUp()
        request = Request({
            'SERVER_PROTOCOL': 'testprotocol',
            'SERVER_NAME': 'test server name',
            'SERVER_PORT': '80',
        })
        request.context = TestContext()
        request.root = request.context
        request.subpath = ['path']
        request.traversed = ['traversed']
        request.view_name = 'test view name'
        request.path_info = 'test info'
        request.scheme = 'https'
        request.host = 'test.com'
        request.registry = get_current_registry()
        self.request = request
        self.data = {}
        self.createDefaultData()
        self.request.userAccount = self.data['user'].userAccount

    @mock.patch('pulse.wapi.wapiUtilities.pyramid.threadlocal.get_current_request')
    @mock.patch('pulse.wapi.wapiUtilities.securityLog')
    def testHasRequest_raises400AndLogsError(
            self, securityLog, get_current_request):
        # Arrange
        get_current_request.return_value = self.request
        self.loggedInUser = self.data['user']
        self.config.testing_securitypolicy(
            userid=self.data['user'].userAccount.id, permissive=True
        )

        with self.assertRaises(exception.HTTPBadRequest):
            from pulse.wapi.wapiUtilities import logSuspiciousRequestAndRaiseHTTPError
            logSuspiciousRequestAndRaiseHTTPError()
            self.assertTrue(securityLog.called)
            self.assertTrue(securityLog.return_value.info.called)

因为authenticated_userid是来自底层认证策略的具体化属性,所以在做测试时不能直接在DummyRequest中设置。这意味着以下两个 都不起作用 :

# Will NOT work
dummy_request = DummyRequest(authenticated_userid='mock_user')
# Also will NOT work
dummy_request = DummyRequest()
dummy_request.authenticated_userid = 'mock_user'

相反,如果我们希望能够控制测试的 authenticated_userid(或身份验证策略的其他方面),我们需要为我们正在测试的测试更改底层金字塔配置运行。为此,您需要查看 pyramid.testing.setUp (docs here). This returns a config object that can do a whole bunch of things, but the important one for our interests is the testing_securitypolicy method (docs here).

testing_securitypolicy 允许我们非常精细地控制从身份验证的角度来看请求的方式。查看它的文档了解细节,但是有了它我们可以设置 authenticated_userid 将用于请求,让它忽略权限要求,等等。

这是一个测试中的用法示例:

from pyramid.testing import (setUp, tearDown, DummyRequest)

def test_some_view():
    config = setUp()
    config.testing_securitypolicy(userid='mock_user')  # Sets authenticated_userid

    dummy_request = DummyRequest()
    print(dummy_request.authenticated_userid)  # Prints 'mock_user'

    # Now ready to test something that uses request.authenticated_userid
    from mypyramidapp.views.secure import some_auth_view
    result = some_auth_view(dummy_request)
    expected = 'Hello mock_user!'
    assert result == expected

    # Finally, to avoid security changes leaking to other tests, use tearDown
    tearDown()  # Undo the effects of pyramid.testing.setUp()