Python flask class Main and MainTest unittest gives error "Ran 0 tests in 0.000s"

I'm creating a Python script that uses flask to give me an API that shows historic facts and a joke for each day. The API is working fine. I can go to http://127.0.0.1:5000/api/v1/resources/today/all to get all days as json, as expected.

Now I want to build a unittest for the API and here is my problem. The unittest gives me "Ran 0 tests in 0.000s".

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()

The test gives me the following:

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

1 answer

  • answered 2022-05-04 10:56 Daweo

    You need to use .assertSomething methods of instance rather than assert statement, so in your case

    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))
    

    c.f. BasicExample in unittest docs

How many English words
do you know?
Test your English vocabulary size, and measure
how many words do you know
Online Test
Powered by Examplum