2016-09-03 3 views
0

그래서 사용자가 로그인하면 그는 가입 할 수없는 웹 앱을 가지고 있습니다. 대신 그는 리디렉션되며 가입 할 수 없다는 메시지가 깜박입니다.플라스크 테스트 계속 실패

문제는 어떤 이유로 테스트 할 수 없다는 것입니다. 여기

내가

def test_signup_page_requires_logout(self): 
    data_to_signup = {'username': 'mustafa1', 'password': 'mustafa1', 
      'confirm_password': 'mustafa1'} 
    data_to_login = {'username': 'mustafa1', 'password': 'mustafa1'} 
    # with statement preserves the request context for the current_user 
    with self.client: 
     self.client.post('/signup', data=data_to_signup) 
     self.client.post('/login', data=data_to_login) 
     response = self.client.get('/signup', follow_redirects=True) 
     assert b'You cannot sign up while you\'re logged in' in response.data 

은 무엇 더욱 혼란 것은이 구조는 다른 방법

def test_headquarter_after_login(self): 
    data_to_signup = {'username': 'mustafa1', 'password': 'mustafa1', 
      'confirm_password': 'mustafa1'} 
    data_to_login = {'username': 'mustafa1', 'password': 'mustafa1'} 
    with self.client: 
     self.client.post('/signup', data=data_to_signup) 
     self.client.post('/login', data=data_to_login) 
     response = self.client.get('/headquarter') 
     assert b'Headquarter page' in response.data 

작동한다는 것이다이 방법이 내 테스트 모듈에서 지금보기

@users_template.route('/signup', methods=['GET', 'POST']) 
def signup(): 
    form = RegisterationForm() 
    if current_user.is_authenticated and current_user.is_active: # prevent the user from seeing the register page if he's already logged in 
     flash('You cannot sign up while you\'re logged in') 
     return redirect(url_for('main.home')) 

    if request.method == 'POST' and form.validate_on_submit(): 
     username = form.username.data 
     password = form.password.data 
     user = User(username=username, password=password) 
     if db.session.query(User).filter(User.username == username).first() is None: 
      current_app.logger.info('<{}> did not register before. Registering him/her now'.format(username)) 
      db.session.add(user) 
      db.session.commit() 
      flash('Thank you for registering. Please login now') 
      return redirect(url_for('users.login')) 
     else: # the user name has been registered before 
      flash('You already registered') 
    return render_template('signup.html', form=form) 

입니다 편집 : 여기에 로그인보기가 있습니다

,451,515,
from .. import bcrypt 
@users_template.route('/login', methods=['GET', 'POST']) 
def login(): 
    form = LoginForm(request.form) 
    if form.validate_on_submit() and request.method == 'POST': 
     username = form.username.data 
     password = form.password.data 

     user = User.query.filter(User.username == username).first() 

     if user is not None and bcrypt.check_password_hash(user.password, password): # authenticate 
      login_user(user) # then log the user in 
      flash('You are logged in') 
      return redirect(url_for('main.home')) 

     else: 
      flash('Incorrect username or password') # if username is wrong, it will be caught by the error handling above 
    return render_template('login.html', form=form) # for a GET request 

이 오류 인이 내 모든 템플릿에서 플래싱이 메시지를 (그것은 내가 상속 내 "base.html"에서의 표시하는 것입니다

  assert current_user.is_active() == True 
      assert current_user.is_authenticated() == True 
>   assert b'You cannot sign up while you\'re logged in' in response.data 
E   AssertionError: assert b"You cannot sign up while you're logged in" in b'<!DOCTYPE html>\n<html lang="en">\n <head>\n <meta charset="utf-8">\n <meta http-equiv="X-UA-Compatible" cont...jquery/1.12.4/jquery.min.js"></script>\n <script src="/static/js/bootstrap.min.js"> </script>\n </body>\n</html>\n' 
E   + where b'<!DOCTYPE html>\n<html lang="en">\n <head>\n <meta charset="utf-8">\n <meta http-equiv="X-UA-Compatible" cont...jquery/1.12.4/jquery.min.js"></script>\n <script src="/static/js/bootstrap.min.js"> </script>\n </body>\n</html>\n' = <TestResponse 3874 bytes [200 OK]>. 

(나는 참고하시기 바랍니다 py.test 사용하고 있습니다))

{% if get_flashed_messages() %} 
     {% for message in get_flashed_messages() %} 
      <div class='container'> 
        <span class='alert alert-info'> 
         <small>{{ message }}</small> 
        </span> 
      </div> 
     {% endfor %} 
    {% endif %} 

나는 플래싱이 메시지를 사용하여 더 많은 테스트를했습니다 그리고 그것은 괜찮 았는데. 어떤 사용자 가입을

assert b'Thank you for registering. Please login now' in response.data 
+1

도보기 로그인 여기 붙여주세요. – turkus

+0

@turkus 완료되었습니다 – MAA

답변

1

제안을 테스트하기 위해이 같은 :이 때문에 라인의

  1. 은 :

    if current_user.is_authenticated and current_user.is_active: 
    

    CURRENT_USER 그의 is_active 플래그는 False로 설정하고있다. 내가 옳지 않다면, 시험 오류를 붙여주세요.

  2. 또 다른 단서는 홈 템플릿의 플래시 메시지 부족 일 수 있습니다.

    {% macro render_flashMessages() %} 
        {% with messages = get_flashed_messages() %} 
         {% if messages %} 
         <ul class="list-unstyled"> 
          {% for message in messages %} 
          <li><div class="alert alert-info">{{ message|safe }}</div></li> 
          {% endfor %} 
         </ul> 
         {% endif %} 
        {% endwith %} 
    {% endmacro %} 
    

    은 다음 home.html이 방법을 사용할 수 있습니다 : 예 flashMessages.html 위해 아래 코드를 넣어

    {% from "flashMessages.html" import render_flashMessages %} 
    
    {{ render_flashMessages() }} 
    
  3. 다음 일을 확인하는 것은 response.data보다는 뭔가 다른 주장 사용하는 것입니다 당신이 Flask-WebTest를 사용하는 경우, 당신은 시도 할 수 있습니다 :

    assert b'You cannot sign up while you\'re logged in' in response.flashes[0][1] 
    

    flashes 인 경우 :

    요청 중에 플래시 된 메시지가 포함 된 튜플 (카테고리, 메시지) 목록입니다.

  4. 하지만 FlaskWebTest를 사용하지 않을 경우, 당신은 세션을 확인할 수 있습니다

    from flask import session 
    
    session['_flashes'][0][1] 
    
+0

오류가 포함되었습니다. is_active와 is_authenticated는 사실 True – MAA

+0

입니다. 또 다른 단서는 ... – turkus

+0

@MAA는 내 마음 속으로 더 많은 것을 가지고 있기 때문에 그것이 작동하거나 여전히 아무것도하지 못합니다. – turkus