jeudi 23 juin 2016

How do I test an application with a global settings file?

I am writing a Flask application and am in the process of writing tests. In my foo/__init__.py, I read a config file:

from flask import Flask

app = Flask(__name__)

from .conf import read_config    
settings = read_config()

I use foo.settings as a global object throughout my application, which makes testing very difficult.

For example:

import json
from foo import settings
from .helper import get_hosts_status

@app.route("/hosts/status")
def hosts_status():
    assert 'is_production' in settings
    data = {
        "num_hosts_up" : get_hosts_status(settings['is_production'])
    }
    return json.dumps(data)

In the above route, testing the code is very difficult because the settings object is imported from foo, making the code innately stateful. Since settings isn't a parameter to the function, I cannot simply mock the object.

I've been trying to refactor my application, but I cannot seem to avoid using some sort of globally scoped object like this. Is there an accepted way to test functions that rely on global objects like my settings object or is there a way to refactor this that makes it easier to test?

Aucun commentaire:

Enregistrer un commentaire