【问题标题】:loop through all rules in blueprint and check json against file, flask循环遍历蓝图中的所有规则并根据文件、flask 检查 json
【发布时间】:2014-05-06 19:24:17
【问题描述】:

我正在测试一个烧瓶应用程序。我有许多看起来像这样的 approutes:

@bp.route('/place', methods=['GET'])
def get_json():
  ...
  return json.dumps(some_data)

我想要做的是获取这个蓝图,实例化它,并检查所有只转储 json 的方法是否都在转储我在测试用例中期望的 json。到目前为止,我有这个:

from blueprint.my_bp import my_bp

app = Flask(__name__)
app.register_blueprint(my_bp, url_prefix='/test')
my_bp.data = fake_data

def tests():
  with app.test_client() as c:
    for rule in app.url_map.iter_rules():
      if len(rule.arguments) == 0 and 'GET' in rule.methods:
        resp = c.get(rule.rule)
        log.debug(resp)
        log.debug(resp.data)

但是,我有一种方法看起来像这样,因为它没有实现:

@bp.route('/')
def show_summary():
  abort(404)

这将出现在我的测试中,因为它在技术上似乎在方法中包含“GET”。

鉴于此,有没有办法将测试限制为仅包含返回 json 的测试?

【问题讨论】:

    标签: python json unit-testing python-2.7 flask


    【解决方案1】:

    一种方法是测试响应是否返回 JSON。您可以尝试以下方法:

    resp = c.get(rule.rule)
    try:
        json_data = resp.loads(resp.data) # this line will throw exception if not JSON
        log.debug(resp)
        log.debug(json_data)
    except:
        pass
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-08-21
      • 1970-01-01
      • 1970-01-01
      • 2014-04-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多