如何使用pytest测试服务是否正常工作

时间:2019-06-18 22:12:05

标签: python pytest

我有一段代码,必须使用pytest进行测试:

from flask import Flask, render_template
app = Flask(__name__)

# two decorators, same function
@app.route('/')
@app.route('/index.html')
def index():
    return render_template('index.html', the_title='Tiger Home Page')

@app.route('/symbol.html')
def symbol():
    return render_template('symbol.html', the_title='Tiger As Symbol')

@app.route('/myth.html')
def myth():
    return render_template('myth.html', the_title='Tiger in Myth and Legend')

if __name__ == '__main__':
    app.run(debug=True, host='0.0.0.0')

由于我以前从未接触过pytest,所以我不知道该怎么做。我在寻找类似的问题,但没有发现任何提示。有人可以举一个例子或材料来测试上述应用程序吗?

1 个答案:

答案 0 :(得分:0)

这里有很多概念。但是,我将尝试介绍基础知识。您需要指定要执行的测试类型。最常见的是:

  • 单元测试
  • 集成测试
  • 验收测试

单元测试的想法是测试特定功能或方法的行为。它将模拟(返回伪造的数据)该函数的每个依赖项,并尝试将其隔离以确保每当我提供数据X时,它始终会返回我期望的结果。

另一方面,集成测试将完全测试单元测试要避免的功能:功能,服务等之间的集成。这是一个更高级的概念,更难以测试。

最后,验收测试将确保业务逻辑正常运行。因此,它将尝试对您的应用程序执行某些操作,并确保它正在执行您想要的操作。

还有很多其他类型的测试,但是最常见。

关于测试路线,您可以进行单元测试和验收测试。我不认为单元测试在那里有用,因为路由功能中的逻辑总是非常简单。

您可以尝试以下代码段来对路径进行验收测试:

from <your module name> import app

def test():
    app.testing = True
    result = app.post('path_you_want_to_test',
                      data=<data_you_want_to_test>,
                      follow_redirects=True)

这样,您将在result变量中获得该发布请求的结果。