【问题标题】:unit test to check if for a given path a correct context will be returned单元测试以检查给定路径是否将返回正确的上下文
【发布时间】:2011-04-15 21:34:32
【问题描述】:

就像标题一样。我有一个可以手动测试的模型。我在浏览器中输入 url 并从其中一个视图中接收结果。事情是 unittest 应该这样做。

我认为应该有某种方法来创建请求,将其发送到应用程序,然后接收上下文。

【问题讨论】:

    标签: python testing pylons pyramid unit-testing


    【解决方案1】:

    您可以使用 WebTest 包创建功能测试,它允许您将 WSGI 应用程序包装在支持.get().post() 等的TestApp 中。

    有关 Pyramid 的详细信息,请参阅http://docs.pylonsproject.org/projects/pyramid/1.0/narr/testing.html#creating-functional-tests,为后代粘贴此处:

    import unittest
    
    class FunctionalTests(unittest.TestCase):
        def setUp(self):
            from myapp import main
            app = main({})
            from webtest import TestApp
            self.testapp = TestApp(app)
    
        def test_root(self):
            res = self.testapp.get('/', status=200)
            self.failUnless('Pyramid' in res.body)
    

    【讨论】:

    • 这种方式检查整个应用程序,并且在 res 对象中没有关于上下文的任何内容。我需要的测试应该只测试遍历以查看它是否在上下文中返回正确的对象。
    【解决方案2】:

    Pyramid 并没有真正公开测试真实请求和接收内部信息的方法。您可以使用以下方式自己执行遍历器:

    from pyramid.traversal import traverse
    
    app = get_app(...)
    root = get_root(app)
    out = traverse(root, '/my/test/path')
    
    context = out['context']
    

    但是,测试有点做作。使用功能测试来检查返回的页面是否符合您的预期会更相关。

    【讨论】:

      猜你喜欢
      • 2017-03-10
      • 2011-09-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-12-18
      • 2021-02-17
      相关资源
      最近更新 更多