我正在创建一个Python脚本,它使用烧瓶给我一个API,它显示了历史事实和每天的一个笑话。API运行良好。我可以去http://127.0.0.1:5000/api/v1/resources/today/all,像预期的那样,整天都像json一样。
现在,我想为API构建一个单元测试,这是我的问题。单元测试给了我“在0.000 0中运行0次测试”。
Main.py:
import datetime
import flask
from flask import jsonify, request, app
class Main:
app = flask.Flask(__name__) # Creates the Flask application object
app.config["DEBUG"] = True
# Readme
dt = datetime.datetime.today()
print("All days: http://127.0.0.1:5000/api/v1/resources/today/all")
print("Today by ID: http://127.0.0.1:5000/api/v1/resources/today?id=2")
print("Today by month and day: http://127.0.0.1:5000/api/v1/resources/today?month=" + '{:02d}'.format(dt.month) + "&day=" + '{:02d}'.format(dt.day))
# Run app
app.run()
def __init__(self):
# Test data for our catalog in the form of a list of dictionaries.
# Jokes from here: https://www.rd.com/list/short-jokes/
todays = [
{'id': 0,
'month': '05',
'day': '04',
'historic_event': '1670 – A royal charter granted the Hudsons Bay Company a monopoly in the fur trade in Ruperts Land (present-day Canada).',
'joke': 'What’s the best thing about Switzerland? I don’t know, but the flag is a big plus.'},
{'id': 1,
'month': '05',
'day': '05',
'historic_event': '2010 – Mass protests in Greece erupt in response to austerity measures imposed by the government as a result of the Greek government-debt crisis.',
'joke': 'I invented a new word! Plagiarism!'},
{'id': 2,
'month': '05',
'day': '06',
'historic_event': '2002– Founding of SpaceX.',
'joke': 'Did you hear about the mathematician who’s afraid of negative numbers? He’ll stop at nothing to avoid them.'},
]
@app.route('/', methods=['GET'])
def home(self):
return '''<h1>Today</h1>
<p>A prototype API for finding out what happened on this day</p>'''
@app.route('/api/v1/resources/today/all', methods=['GET'])
def api_all(self):
return jsonify(self.todays)
@app.route('/api/v1/resources/today', methods=['GET'])
def api_id(self):
# Check if an ID was provided as part of the URL.
# If ID is provided, assign it to a variable.
# If no ID is provided, display an error in the browser.
if 'id' in request.args:
id = int(request.args['id'])
else:
return "Error: No id field provided. Please specify an id."
# Create an empty list for our results
results = []
# Loop through the data and match results that fit the requested ID.
# IDs are unique, but other fields might return many results
for today in self.todays:
if today['id'] == id:
results.append(today)
# Use the jsonify function from Flask to convert our list of
# Python dictionaries to the JSON format.
return jsonify(results)
Main();
tests/MainTest.py:
import unittest
from Main import app
class MainTest(unittest.TestCase):
def setUp(self):
self.ctx = app.app_context()
self.ctx.push()
self.client = app.test_client()
def tearDown(self):
self.ctx.pop()
def test_home(self):
response = self.client.get("/", data={"content": "hello world"})
assert response.status_code == 200
assert "POST method called" == response.get_data(as_text=True)
if __name__ == "__main__":
unittest.main()
测试给了我以下几点:
C:\Users\s\PycharmProjects\TodayPython\venv\Scripts\python.exe "C:\Program Files\JetBrains\PyCharm Community Edition 2022.1\plugins\python-ce\helpers\pycharm\_jb_unittest_runner.py" --target MainTest.MainTest.test_home
Testing started at 12:46 ...
Launching unittests with arguments python -m unittest MainTest.MainTest.test_home in C:\Users\s\PycharmProjects\TodayPython\tests
All days: http://127.0.0.1:5000/api/v1/resources/today/all
Today by ID: http://127.0.0.1:5000/api/v1/resources/today?id=2
Today by month and day: http://127.0.0.1:5000/api/v1/resources/today?month=05&day=04
* Serving Flask app 'Main' (lazy loading)
* Environment: production
WARNING: This is a development server. Do not use it in a production deployment.
Use a production WSGI server instead.
* Debug mode: on
* Running on http://127.0.0.1:5000 (Press CTRL+C to quit)
* Restarting with stat
Ran 0 tests in 0.000s
OK
Launching unittests with arguments python -m unittest in C:\Users\s\PycharmProjects\TodayPython\tests
Process finished with exit code 0
Empty suite
Empty suite
发布于 2022-05-04 10:56:34
您需要使用.assert
一些实例的方法,而不是assert
statement,所以在您的情况下
def test_home(self):
response = self.client.get("/", data={"content": "hello world"})
self.assertEqual(response.status_code, 200)
self.assertEqual("POST method called", response.get_data(as_text=True))
https://stackoverflow.com/questions/72111778
复制相似问题