2016-08-08 4 views
0

cherrypy.helper.CPWebCase 하위 클래스를 사용하여 CherryPy 서버에 대해 pytest 단위 테스트를 실행하는 경우 세션 개체에 대한 데이터를 어떻게 설정합니까? 나는 것처럼 나는 cherrypy 전화에 정말 있었다면 난 그냥 cherrypy.session['foo']='bar'를 호출 시도,하지만 그건 단지 "AttributeError: '_Serving' object has no attribute 'session'"Python - CherryPy 테스트 - 세션 데이터를 설정 하시겠습니까?

참고로, 테스트 케이스 (사소한 편집으로 the CherryPy Docs에서 가져온) 같은 것을 보일 수 있습니다 주었다

import cherrypy 
from cherrypy.test import helper 
from MyApp import Root 

class SimpleCPTest(helper.CPWebCase): 
    def setup_server(): 
     cherrypy.tree.mount(Root(), "/", {'/': {'tools.sessions.on': True}}) 

    setup_server = staticmethod(setup_server) 

    def check_two_plus_two_equals_four(self): 
     #<code to set session variable to 2 here> 
     # This is the question: How do I set a session variable? 
     self.getPage("/") 
     self.assertStatus('200 OK') 
     self.assertHeader('Content-Type', 'text/html;charset=utf-8') 
     self.assertBody('4') 

그리고이 같은 보일 수 있습니다 핸들러 (또는 다른 것, 그것은 전혀 차이가 없습니다) :

class Root: 
    @cherrypy.expose 
    def test_handler(self): 
     #get a random session variable and do something with it 
     number_var=cherrypy.session.get('Number') 
     # Add two. This will fail if the session variable has not been set, 
     # Or is not a number 
     number_var = number_var+2 
     return str(number_var) 

그것은 설정이 올바른지 가정 안전, 예상대로 세션이 작동합니다.

물론 키와 값을 인수로 사용하는 CherryPy 페이지를 작성한 다음 지정된 세션 값을 설정하고이를 테스트 코드에서 호출 할 수 있습니다 (편집 : 테스트 해봤습니다. 작업). 그러나, 그 길을 따라 가면 어떻게 든 테스트에만 국한시키고 싶습니다.

+0

엔드 포인트에'cherrypy.tools.session'을 사용 가능하게 했습니까? 핸들러와 테스트 케이스의 정확한 코드는 무엇입니까? plz는 미리보기를 제공합니다. – webKnjaZ

+0

예, 세션을 사용하도록 설정되었습니다. 앱이 작동합니다. 테스트를 작성하려고합니다. 내 처리기는 수십 개의 파일과 수천 줄의 코드로 구성되며 여기에 게시하기가 복잡합니다 (특정 부분을 언급하지 않으므로). 테스트 케이스에 관해서는, 그게 내가 묻고있는 것이다. 세션 객체에 값을 설정할 수 있도록 테스트 케이스에 필요한 코드는 무엇인가? 일부 일반적인 테스트 케이스 코드를 게시하는 것이 도움이되지 않는다면? – ibrewster

+0

최소한의 버전을 처리기 및 구성 정보로 게시하여 문제를 재현 할 수 있습니다 (과중한 논리는 모두 무시하십시오). 내 눈으로 세션을 설정하는 방법을보고 싶습니다. 지금 테스트는 정상적으로 보입니다. 사용중인 CherryPy 버전도 확인하십시오. – webKnjaZ

답변

3

달성하려는 목표는 보통 mocking입니다.

테스트를 실행하는 동안 일반적으로 동일한 인터페이스 (오리 입력)가있는 더미 객체로 액세스하는 일부 리소스를 '모의'하고 싶습니다. 이는 원숭이 패치로 얻을 수 있습니다. 이 프로세스를 단순화하기 위해 unittest.mock.patch을 컨텍스트 관리자 또는 메소드/함수 데코레이터로 사용할 수 있습니다.

컨텍스트 관리 옵션을 사용하여 작업을 예를 검색 :

==> MyApp.py < ==

import cherrypy 


class Root: 
    _cp_config = {'tools.sessions.on': True} 

    @cherrypy.expose 
    def test_handler(self): 
     # get a random session variable and do something with it 
     number_var = cherrypy.session.get('Number') 
     # Add two. This will fail if the session variable has not been set, 
     # Or is not a number 
     number_var = number_var + 2 
     return str(number_var) 

==> cp_test.py < ==

from unittest.mock import patch 

import cherrypy 
from cherrypy.test import helper 
from cherrypy.lib.sessions import RamSession 

from MyApp import Root 


class SimpleCPTest(helper.CPWebCase): 
    @staticmethod 
    def setup_server(): 
     cherrypy.tree.mount(Root(), '/', {}) 

    def test_check_two_plus_two_equals_four(self): 
     # <code to set session variable to 2 here> 
     sess_mock = RamSession() 
     sess_mock['Number'] = 2 
     with patch('cherrypy.session', sess_mock, create=True): 
      # Inside of this block all manipulations with `cherrypy.session` 
      # actually access `sess_mock` instance instead 
      self.getPage("/test_handler") 
     self.assertStatus('200 OK') 
     self.assertHeader('Content-Type', 'text/html;charset=utf-8') 
     self.assertBody('4') 

다음과 같이 안전하게 test를 실행할 수 있습니다 :

$ py.test -sv cp_test.py 
============================================================================================================ test session starts ============================================================================================================= 
platform darwin -- Python 3.5.2, pytest-2.9.2, py-1.4.31, pluggy-0.3.1 -- ~/.pyenv/versions/3.5.2/envs/cptest-pyenv-virtualenv/bin/python3.5 
cachedir: .cache 
rootdir: ~/src/cptest, inifile: 
collected 2 items 

cp_test.py::SimpleCPTest::test_check_two_plus_two_equals_four PASSED 
cp_test.py::SimpleCPTest::test_gc <- ../../.pyenv/versions/3.5.2/envs/cptest-pyenv-virtualenv/lib/python3.5/site-packages/cherrypy/test/helper.py PASSED 
+0

물론! cherrypy 스레드 로컬 세션 객체를 내 자신의 글로벌 객체로 대체하십시오! 물론, * 실제 * 세션 객체는 더 이상 사용할 수 없으므로 테스트중인 것뿐만 아니라 테스트 된 함수에서 액세스해야하는 * 값을 설정해야합니다. 그러나 이는 사소한 것입니다. – ibrewster

+0

네, 맞습니다 :) – webKnjaZ