How can I unit test this Flask app?

2024/10/10 22:27:43

I have a Flask app that is using Flask-Restless to serve an API.

I have just written some authentication that checks

  1. If the consumers host is recognised
  2. The request includes a hash (calculated by encrypting the request content for POST and URL for GET along with a secret API key) and
  3. The hash is valid

I want to be able to write some unit tests for this, but I'm not sure how because my functions use the request object. Should I be mocking the request object?

Would love some advice on this.

Config

API_CONSUMERS = [{'name': 'localhost','host': '12.0.0.1:5000','api_key': 'Ahth2ea5Ohngoop5'},{'name': 'localhost2','host': '127.0.0.1:5001','api_key': 'Ahth2ea5Ohngoop6'}]

Authentication methods

import hashlib
from flask import requestdef is_authenticated(app):"""Checks that the consumers host is valid, the request has a hash and thehash is the same when we excrypt the data with that hosts api keyArguments:app -- instance of the application"""consumers = app.config.get('API_CONSUMERS')host = request.hosttry:api_key = next(d['api_key'] for d in consumers if d['host'] == host)except StopIteration:app.logger.info('Authentication failed: Unknown Host (' + host + ')')return Falseif not request.headers.get('hash'):app.logger.info('Authentication failed: Missing Hash (' + host + ')')return Falseif request.method == 'GET':hash = calculate_hash_from_url(api_key)elif request.method == 'POST':hash = calculate_hash_from_content(api_key)if hash != request.headers.get('hash'):app.logger.info('Authentication failed: Hash Mismatch (' + host + ')')return Falsereturn Truedef calculate_hash_from_url(api_key):"""Calculates the hash using the url and that hosts api keyArguments:api_key -- api key for this host"""data_to_hash = request.base_url + '?' + request.query_stringdata_to_hash += api_keyreturn hashlib.sha1(request_uri).hexdigest()def calculate_hash_from_content(api_key):"""Calculates the hash using the request data and that hosts api keyArguments:api_key -- api key for this host"""data_to_hash = request.datadata_to_hash += api_keyreturn hashlib.sha1(data_to_hash).hexdigest()
Answer

test_request_object() did the trick, thanks monkey.

from flask import requestwith app.test_request_context('/hello', method='POST'):# now you can do something with the request until the# end of the with block, such as basic assertions:assert request.path == '/hello'assert request.method == 'POST'
https://en.xdnf.cn/q/69844.html

Related Q&A

How to completely reset Python stdlib logging module in an ipython session?

Id like to make repeated calls to Python scripts using %run in an ipython session, and for each of those scripts to log based on cmdline arguments passed via %run.For example while debugging cmd.py I m…

I think Librosa.effect.split has some problem?

firstly, this function is to remove silence of an audio. here is the official description:https://librosa.github.io/librosa/generated/librosa.effects.split.htmllibrosa.effects.split(y, top_db=10, *karg…

Replace None in list with leftmost non none value

Givena = [None,1,2,3,None,4,None,None]Id likea = [None,1,2,3,3,4,4,4]Currently I have brute forced it with:def replaceNoneWithLeftmost(val):last = Noneret = []for x in val:if x is not None:ret.append(x…

Generating lists/reports with in-line summaries in Django

I am trying to write a view that will generate a report which displays all Items within my Inventory system, and provide summaries at a certain point. This report is purely just an HTML template by the…

How to test if a view is decorated with login_required (Django)

Im doing some (isolated) unit test for a view which is decorated with "login_required". Example:@login_required def my_view(request):return HttpResponse(test)Is it possible to test that the &…

Filter Nested field in Flask Marshmallow

I want to filter the nested field with is_active column as True in Marshmallow 3 Consider following scenario I have 3 tablesusers (id, name) organizations (id, name) organization_user(id, organization_…

Copy signature, forward all arguments from wrapper function

I have two functions in a class, plot() and show(). show(), as convenience method, does nothing else than to add two lines to the code of plot() likedef plot(self,show_this=True,show_that=True,color=k,…

How to fit a line through a 3D pointcloud?

I have a cable I am dropping from moving vehicle onto the ground. Using a camera system I estimate the location where the rope touches the ground in realtime. Movement of the vehicle and inaccuracy in …

Websockets with Django Channels on Heroku

I am trying to deploy my app to heroku. The app has a simple chatting system that uses Websockets and django channels. When I test my app using python manage.py runserver the app behaves just as intend…

How can I get the name/file of the script from sitecustomize.py?

When I run any Python script, I would like to see the scripts filename appear in the Windows command line windows titlebar. For example, if I run a script called "mytest.py", I want to see &q…