测试 webapp2:无法识别需要登录

Testing webapp2: Login required not recognized

我在app.yaml

中有以下内容
handlers:
- url: /.*
  script: app.application
  secure: always
  login: required

当 运行 测试时,我正在按照 google 的建议使用此 testrunner

class SearchTest(unittest.TestCase):
    def setUp(self):

        # Set up app simulator
        app = webapp2.WSGIApplication([('/search', search.Search)], debug=True)
        self.testapp = webtest.TestApp(app)

        # Google testbed
        self.testbed = testbed.Testbed()
        self.testbed.activate()

        self.testbed.init_user_stub()
        self.testbed.init_datastore_v3_stub()
        self.testbed.init_memcache_stub()

        # Disable caching to prevent data from leaking between tests
        ndb.get_context().set_cache_policy(False)


    def testNotLoggedin(self):
        # Test user is redirected to login when not logged in

        assert not users.get_current_user()

        response = self.testapp.get('/search')
        self.assertEqual(response.status_int, 302)
        assert response.headers['Location']

testNotLoggedIn 失败,返回 200 != 302。因此即使需要登录,用户似乎仍然可以访问。这让我觉得 app.yaml 在测试中没有被识别?

如何确保 app.yaml 被识别并且用户需要登录?

此测试代码绕过 app.yaml 分派。在 App Engine(和开发服务器)上,HTTP 请求通过 app.yaml 路由到 WSGI 应用程序实例,处理 login: required 的前端逻辑发生在调用请求处理程序之前。在此测试代码中,您将直接转到 WSGI 应用程序:self.testapp.get('/search') 只是调用 WSGI 应用程序自己的内部 URL 映射以到达 search.Search 请求处理程序。

您要测试的条件更像是集成测试,需要 运行 开发服务器或已部署的 App Engine 测试版本。这是个好主意,只是比 testbed 等人所能做的更大。