Start learning free

LESSON 144 OF 173 · BACKEND: TESTS AND RUNNING IT

Settings per Environment in Go

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 every program it starts can read.

You read one with os.Getenv: it gives the text, or "" when the variable isn't set, so you pick a default yourself. In a test, s.Setenv works like Go's t.Setenv: it sets a variable until the test ends, then puts the old value back. Here a shop picks its currency:

currency := os.Getenv("SHOP_CURRENCY")
if currency == "" {
    currency = "USD"
}

func (s *PriceTests) TestEuro() {
    s.Setenv("SHOP_CURRENCY", "EUR")
    fmt.Println(os.Getenv("SHOP_CURRENCY"))   // EUR
}

The setting that matters most is debug mode, config.Debug. A shop in debug mode answers a crash with all its details, the error and where in your code it happened: 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
loadConfig on your computer, with SHOP_ENV=development:
  DEBUG = true
loadConfig on the server, with SHOP_ENV=production:
  DEBUG = false
loadConfig on a server where nobody set SHOP_ENV:
  DEBUG = false
loadConfig with SHOP_ENV=Development, a typo:
  DEBUG = false
Your tests on the shop:
  TestDebugOffInProduction ... ok
  1 test: OK
Your tests on a copy that keeps debug mode on everywhere:
  TestDebugOffInProduction ... FAIL
    Should be false
  1 test: 1 failed, so they caught this bug

Your task: write loadConfig, a function kept in a variable, which reads SHOP_ENV with the default "production" and returns a Config whose Debug is true only for development. The given line var config = loadConfig() loads the shop's own settings when it starts. Then write TestDebugOffInProduction, which loads the settings 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 put it straight in the Config. In the test, keep the result of loadConfig() in a new testConfig instead of changing the shop's config, and check it with s.False.


STEP 1 OF 9
    Ctrl + Enter to check

    Ops Config in Go

    Keep going with Go1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free