我想测试蓝图中的所有路由是否都需要登录必需的装饰器保护。
重点是: 如果开发人员添加一条新路线而忘记添加此装饰器,我希望我的测试能够自动发现该缺失。
为此,我想遍历所有路由和方法
for rule in app.url_map.iter_rules():
if rule.endpoint.startswith("my_blueprint"):
response = app.test_client().get(rule)
assert response.status_code == 401
如您所见,我必须像这样app.test_client().get(rule)
指定方法(获取,发布..)。
是否有更动态的方法来调用方法?
答案 0 :(得分:3)
发现功能
class cub
{
public int cubWeight = 150;
public int cubHeight = 150;
public void createNewCub()
{
Label cubLabel = new Label();
cubLabel.Size = new Size(cubWeight, cubHeight);
cubLabel.Text = "GeeksforGeeks";
cubLabel.Location = new Point(500, 200);
cubLabel.Font = new Font("Calibri", 18);
cubLabel.ForeColor = Color.Green;
cubLabel.Padding = new Padding(6);
}
}
public Form1()
{
InitializeComponent();
label1.Text = "Number of cubs: " + trackBar1.Value;
label2.Text = "Number of seconds: " + trackBar2.Value;
cub xxx = new cub();
xxx.createNewCub();
样本输出
def blueprint_site_map(app, blueprint, all_methods=False):
'''
utilizes Flask's built-in rule mapper to generate a
site-map of the application, returning a list of dicts, ex.
{
'endpoint' : repr(Blueprint)
'methods' : list
'rule' : /route
{
'''
reply = []
rules = list(app.url_map.iter_rules())
ignored_methods = set(() if all_methods else ('HEAD', 'OPTIONS'))
rule_methods = [','.join(sorted(rule.methods - ignored_methods)) for rule in rules]
for rule, methods in zip(rules, rule_methods):
if (rule.endpoint != 'static') and (rule.endpoint.startswith(blueprint)):
reply.append(dict(endpoint=rule.endpoint, methods=methods.split(','), rule=rule.rule))
return reply
用法
>>> blueprint_site_map(app, 'my_blueprint')
[
{
'endpoint': 'my_blueprint.foo',
'methods': ['GET', 'POST'],
'rule': '/auth/foo'
},
{
'endpoint': 'my_blueprint.bar',
'methods': ['DELETE', 'GET', 'POST'],
'rule': '/auth/bar'
}
]
请注意,如果您使用任何参数化的URL规则,例如同时允许def test_my_blueprint_is_protected(client):
from flask import current_app as app
obj = blueprint_site_map(app, 'my_blueprint')
for each in obj:
for method in each['methods']:
func = getattr(client, method)
url = each['rule'] # *see note
kwargs = {} # inject headers, etc if needed
response = func(url, **kwargs)
assert response.status_code == 401
和/foo
,那么您将需要手动模板化或过滤掉它们。 /foo/<string:s>
函数将包含blueprint_site_map
和/foo
的单独的列表元素,从字面上看将导致测试客户端本身或路由逻辑出现问题。
发现功能的构建方式使您可以根据需要将约定用于尽可能多的不同蓝图,这就您使用蓝图约定的本质而言,意味着您可以将单元测试保持与应用程序一样模块化。
干杯!