Unit testing Flask app running under uwsgi

2024/11/14 23:40:36

I’m relatively new to python and am looking for a pythonic way to handle this practice.

I’ve inherited a fairly trivial Python 2.7 Flask app that runs under uwsgi that I want to add some unit tests to. It does some initialization at indentation level 0 that is required when it’s running in uwsgi but needs to be skipped when under test.

I’m given to understand that often python apps use the

if __name__ == '__main__':

pattern to isolate code that should run when the script is run on its own and should not run when it’s imported. In this case, however, both when the script is run under uwsgi and when the script is imported into the unit tests, __name__ is the same; the name of the script, so I can’t use that to differentiate between uwsgi and unit-testing environments.

This sample code illustrates what I'm working with.

In the Flask application (flask_app.py):

import logging
import bcrypt
from flask import Flask, jsonify, abort, make_response, request
from ConfigParser import SafeConfigParser#  some initialization that only makes sense when running from the uwsgi context on the server
PARSER = SafeConfigParser()
PARSER.read('config.ini')
LOG_FILE = PARSER.get('General', 'logfile')APP = Flask(__name__)@APP.route('/', methods=['GET'])
def index...@APP.route('/<p1>/<p2>', methods=['PUT'])
def put(p1, p2):...if __name__ == '__main__':APP.run(debug = True, host='0.0.0.0')

In the unit tests (tests.py):

import os
import unittest
from flask import jsonfrom flask_app import APPclass FlaskAppTestCase(unittest.TestCase):def setUp(self):self.APP = APP.test_client()def test_GET(self):resp = self.APP.get('/')assert 'Some Html' in resp.datadef test_PUT(self):resp = self.APP.put('/1/2')assert 'Got 1, 2' in resp.dataif __name__ == '__main__':unittest.main()

What I was thinking of doing was to move the initialization so that it only runs when flask_app is being executed by uwsgi and not when it's running via tests.py, perhaps by checking name and determining which path to execute based on that, but when I examine the output of print(name) either when running flask_app under uwsgi or by executing tests.py the output is "flask_app", so I can't seem to use that as a discriminator.

Is there an idiomatic way in python to handle this?

Answer

As it turns out the Python module for uWSGI actually offers a mechanism to determine if the app is being run under uWSGI. The uwsgi module is available for import if you are in a uWSGI context, so I ended up checking whether i could import that module and only executing the initialization code if I could.

#   detect if we're running under uWSGI; only init if we are, not if we're testing
try:import uwsgiIN_UWSGI = True
except ImportError:IN_UWSGI = False

Then wrap the init code with

if IN_UWSGI:

This seems much more reliable then checking the module name of the module that's doing the import, which was the only other thing I could think of to do.

https://en.xdnf.cn/q/71494.html

Related Q&A

fastest way to find the smallest positive real root of quartic polynomial 4 degree in python

[What I want] is to find the only one smallest positive real root of quartic function ax^4 + bx^3 + cx^2 + dx + e [Existing Method] My equation is for collision prediction, the maximum degree is quarti…

Split strings by 2nd space

Input :"The boy is running on the train"Output expected:["The boy", "boy is", "is running", "running on", "on the", "the train"]Wha…

Searching for a random python program generator

Im searching for a program that can generate random but valid python programs, similar to theRandom C program generator. I was trying to do this myself giving random input to the python tokenize.untoke…

Python tk framework

I have python code that generates the following error:objc[36554]: Class TKApplication is implemented in both /Library/Frameworks/Tk.framework/Versions/8.5/Tk and /System/Library/Frameworks/Tk.framewor…

SQLAlchemy relationship on many-to-many association table

I am trying to build a relationship to another many-to-many relationship, the code looks like this: from sqlalchemy import Column, Integer, ForeignKey, Table, ForeignKeyConstraint, create_engine from …

Python: interpolating in a triangular mesh

Is there any decent Pythonic way to interpolate in a triangular mesh, or would I need to implement that myself? That is to say, given a (X,Y) point well call P, and a mesh (vertices at (X,Y) with val…

Customizing pytest junitxml failure reports

I am trying to introspect test failures and include additional data into the junit xml test report. Specifically, this is a suite of functional tests on an external product, and I want to include the p…

python nltk keyword extraction from sentence

"First thing we do, lets kill all the lawyers." - William ShakespeareGiven the quote above, I would like to pull out "kill" and "lawyers" as the two prominent keywords to …

Getting the parameter names of scipy.stats distributions

I am writing a script to find the best-fitting distribution over a dataset using scipy.stats. I first have a list of distribution names, over which I iterate:dists = [alpha, anglit, arcsine, beta, bet…

Does Python 3 gzip closes the fileobj?

The gzip docs for Python 3 states thatCalling a GzipFile object’s close() method does not close fileobj, since you might wish to append more material after the compressed dataDoes this mean that the g…