本文介绍了如何使 view_config 装饰器与金字塔单元测试一起工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我为金字塔网络框架编写了一个 login_required 装饰器.在金字塔测试服务器中它运行良好.

I wrote a login_required decorator for the pyramid web framework. In a pyramid test server it works well.

但在 Pyramid 单元测试中,@view_config 装饰器不适用于所有配置(不仅是装饰器参数).

But in the Pyramid unit tests for the @view_config decorator do not work for all configurations (not only the decorator parameter).

这是代码:

class MyViews(object):
  @view_config(decorator=login_required(login_url=LOGIN_URL),
               match_param="action=change_password", request_method="GET",
               renderer="accounts/change_password.jinja2")
    def change_password(self):
        form = ChangePwdForm()
        return {'form': form}

测试代码如下:

def test_change_password_fail(self):
        from .views import AccountsViews
        aviews = AccountsViews(testing.DummyRequest(path='/accounts/forget_password'))
        response = aviews.forget_password()
        self.assertEqual(response.status_code, 307)  #HTTPTemporaryRedirect

我例外的是 not-logined-user 将被重定向到登录 url.@view_config 中的所有参数,例如 renderer 和 'match_param' 都不起作用.

What i excepted was that the not-logined-user will be redirected to login url.All paramenters in @view_config such as renderer and 'match_param' do not work.

我该如何解决这个问题?

How can I solve this problem?

参考文献:
使用金字塔模拟渲染响应
单元和集成测试:Pyramid 官方指南,但是不是指基于类的视图的装饰器问题

References:
Mocking render to response with Pyramid
Unit and Integration Testing:Pyramid official guide,but not refer to class-based view's decorator problem

推荐答案

@view_config() 在您运行 config.scan() 之前不会被应用.

@view_config() does not get applied until you run a config.scan().

当您进行测试时,通常您想测试单个单元,在这种情况下是视图,而不用担心框架的其余部分.

When you are doing testing, in general you want to test a single unit, in this case the view without worrying about the rest of the framework.

您将分别测试您的视图和装饰器.

You'd test your view and your decorator separately.

一旦您达到更高级别,并且想要测试 Pyramid 是否为您的视图做正确的事情,您将想要进行集成测试.通过集成测试,您将设置完整的配置器对象,以及完整的应用程序,虽然繁重,但允许您测试 Pyramid 是否应用了装饰器.

Once you get to the higher level, and want to test that Pyramid is the doing the right thing for your views, you will want to do integration testing. With integration testing you will set up the full configurator object, and the full app, it is more heavy handed, but allows you to test that Pyramid applies the decorator.

您需要的最后一个测试是模拟完整应用程序的完整端 2 端测试.最新文档位于:http://docs.pylonsproject.org/docs/pyramid/en/latest/narr/testing.html

The last tests you would want are full end 2 end tests that emulate the full application. The latest documentation is available at: http://docs.pylonsproject.org/docs/pyramid/en/latest/narr/testing.html

这篇关于如何使 view_config 装饰器与金字塔单元测试一起工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-26 15:47