Start learning free

LESSON 144 OF 188 · BACKEND: TESTS AND RUNNING IT

Settings per Environment

Practice

Your shop runs in two places with the same code: on your computer while you build it, the development environment, and on the server where customers use it, production. Only a few settings differ. The server tells the program where it runs with an environment variable, a named text value that Python keeps in the dictionary os.environ.

You read one with os.environ.get: the name, then a default for when it isn't set. In a test, patch.dict from unittest.mock sets a variable only for the lines inside a with block, and puts the old values back when the block ends. Here a shop picks its currency:

currency = os.environ.get("SHOP_CURRENCY", "USD")

with patch.dict(os.environ, {"SHOP_CURRENCY": "EUR"}):
    print(os.environ["SHOP_CURRENCY"])   # EUR

The setting that matters most is debug mode, app.config["DEBUG"]. When a request crashes, debug mode shows the error, your code and a Python console right in the browser: handy on your computer, a disaster on the server. So it must be on only when SHOP_ENV is exactly development, and off for production, for a missing variable and for a typo.

The check starts your shop with SHOP_ENV=development, calls your function in each case, and runs your test on the shop and on a copy that keeps debug mode on everywhere. It must print:

Your shop, started on your computer with SHOP_ENV=development:
  DEBUG = True
load_config on your computer, with SHOP_ENV=development:
  DEBUG = True
load_config on the server, with SHOP_ENV=production:
  DEBUG = False
load_config on a server where nobody set SHOP_ENV:
  DEBUG = False
load_config with SHOP_ENV=Development, a typo:
  DEBUG = False
Your tests on the shop:
  test_debug_off_in_production ... ok
  1 test: OK
Your tests on a copy that keeps debug mode on everywhere:
  test_debug_off_in_production ... FAIL
    AssertionError: True is not false
  1 test: 1 failed, so they caught this bug

Your task: write load_config(app), which reads SHOP_ENV with the default "production" and sets app.config["DEBUG"], and call it for the shop's app. Then write ConfigTests with test_debug_off_in_production, which loads the settings into a new app with SHOP_ENV set to production and checks that debug mode is off.


Assignment
Follow the Coding Tutorial to load the shop's settings from SHOP_ENV and write the test that keeps debug mode off in production.


Hint
A comparison is already True or False, so you can store it straight in the setting. In the test, make a new Flask(__name__) app instead of changing the shop's, call load_config inside the with block, and check the setting below it with self.assertFalse.


STEP 1 OF 9
    Ctrl + Enter to check