Flask - web development

Test Blueprints

Must be called from the primary directory or your app will not be found. The directory containing the app directory
Test files go in test directory (in this case app/blueprints/matchmaking/tests) with names starting with test_ (ie test_matchmaking.py)

python3 -m unittest discover app/blueprints/matchmaking/tests


Example starter file:


import unittest
import inspect
from flask import current_app
from app import create_app
from slg_utilities.helpers import prnt, print_object_attrs, print_items
from config import Config

class TestConfig(Config):
    TESTING = True
    MONGODB_SETTINGS = {
        # "db": "doodler-backend-testing",
        "host": "mongodb://127.0.0.1:27017/doodler-backend-testing"
        # "host": "mongodb://127.0.0.1:27017/doodler-website"
    }
    GAME_SERVER_AUTHENTICATION_KEY = "my-test-secret-key"

class TestLoadDataFunctions(unittest.TestCase):

    # @classmethod
    # def setUpClass(cls):
    #     cls.shared_resource = random.randint(1, 100)

    # @classmethod
    # def tearDownClass(cls):
    #     cls.shared_resource = None

    def setUp(self):
        self.app = create_app(TestConfig)
        self.appctx = self.app.app_context()
        self.appctx.push()
        self.client = self.app.test_client()

    def tearDown(self):
        self.appctx.pop()
        self.app = None
        self.appctx = None

    def test_app(self):
        assert self.app is not None
        assert current_app == self.app

    def test_game_created_error_with_incorrect_key(self):
        resp = self.client.get('/game_created_successfully', query_string={'players': ['1','2'], 'key': 'secret-key-for-game-creation'})
        prnt(resp.json)
        self.assertEqual(resp.json['success'], False)

        

Getting request data

# POST requests
request.form

# GET requests
request.args

# Receive list from query params
request.args.to_dict(flat=False)

        

Pass JSON object as a dictionary

In the javascript:
$.ajax({
    url: '/endpoint',
    contentType: "application/json; charset=utf-8",
    data : JSON.stringify(data),
    method: "POST",
    success: function(result) {
    }
});

In the flask app:
@app.route('/endpoint', methods=['POST'])
def endpoint():
    print(request.json)

        

Get class name or do equivalency check of LocalProxy flask object

if current_user._cls == 'UnregisteredUser' or current_user._cls == 'User':
    pass
        

Flask-Assets important functionality information

Bundles are only created upon page visit.
My original assumption was that the distribution static assets would be bundled upon app initialization but that's not true.