烧瓶测试 - 功能测试错误 - 响应流[400 BAD REQUEST]

时间:2015-12-26 22:40:35

标签: python flask flask-wtforms

我正试图用烧瓶客户端测试烧瓶应用。

我的应用路由处理如下

@app.route('/', methods=['post', 'get'])
@app.route('/index', methods=['post', 'get'])
def index():

   login_form = LoginForm(request.form)
   logout_form = LogoutForm(request.form)
   short_url_form = ShortURLForm(request.form)


   if request.method == 'POST' and short_url_form.validate():
       url = short_url_form.url.data
       url_shortener_handler = urlShortener()

       app.logger.debug('in post method to shorten Url(%s)', url)

       # TODO have a mechanism for handling duplicate key error
       short_url = url_shortener_handler.generateShortUrl()

       if url_shortener_handler.saveUrl(short_url, url):
           app.logger.debug('value of short url(%s) for url is (%s)', short_url, url)
           return render_template('index.html',
                               login_form=login_form,
                               logout_form=logout_form,
                               shorturl_form=short_url_form,
                               shortURL=SITE_URL + '/' + short_url)
       else:
          app.logger.critical('Error in saving short url(%s) for url is (%s)', short_url, url)
          flash('Internal error try again')

    return render_template('index.html',
                       login_form=login_form,
                       logout_form=logout_form,
                       shorturl_form=short_url_form,
                       shortURL=None)

short_url_form定义如下

class ShortURLForm(Form):

    url = StringField('url', validators=[url(), data_required()])
    submit = SubmitField('Shorten')

    def __init__(self, *args, **kwargs):
       Form.__init__(self, *args, **kwargs)

    def validate(self):
       """  performs validation of input  """
       if not Form.validate(self):
          return False
       return True

我正在使用以下测试用例进行测试

 class TestBasicUrlShortener(unittest.TestCase):
    def setUp(self):
       self.client = app.test_client()
       self.baseURL = 'http://localhost:5000'

    def create_app(self):
         """  this is one of the functions that must be implemented for flask testing. """
        app = Flask(__name__)
        app.config['TESTING'] = True
        app.config['WTF_CSRF_ENABLED'] = False
        WTF_CSRF_ENABLED = False
        app.debug = True
        self.baseURL = 'http://localhost:5000'
        return app

当我使用客户端发送帖子请求时,我收到400个错误请求。

     def test_post_to_urlshortener(self):
        """   When we send a post we expect it to return a output
         containing the baseURL and short url """

         # monkeypatch the generate shortURL so that we know
         # the correct value to expect and perform validation
         # accordingly
         from app.models import urlshortener

          urlshortener.urlShortener.generateShortUrl = self.generate_shortURL
         data = dict(url='http://www.google.com/', submit='Shorten')

          rv = self.client.post('/',
                          data=data,
                          follow_redirects=False)
          print rv
          self.assertEqual(rv.status_code, 200)
          shorturl = self.baseURL + '/' + self.generate_shortURL()
          # print rv.data
          assert shorturl in str(rv.data)

          # cleanup so next time it works
          urlshort = urlshortener.urlShortener()
          urlshort.removeUrl(self.generate_shortURL())

当我用浏览器测试代码时,代码工作,测试中缺少唯一的参数,浏览器是csrf token.However我已经使用配置禁用了csrf保护(希望如此)

欢迎任何有助于缩小问题的指示。

1 个答案:

答案 0 :(得分:1)

问题似乎是,即使禁用了csrf_token,wtf-form也会引发错误,如问题https://github.com/lepture/flask-wtf/issues/208

中所述

我所做的是制作代码,解析输出并提取csrf_token。代码如下

    def getcsrf_value(self):

    """ get csrf token """

    rv = self.client.get('/')

    soup = BeautifulSoup(rv.data, 'html.parser')
    tag = soup.body.find('input', attrs={'name' : 'csrf_token'})
    return tag['value']