tmpenv

package module
v1.0.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Apr 25, 2019 License: MIT Imports: 1 Imported by: 0

README

tmpenv

Build Status codecov Documentation

Easily set temporary environment variables and commandline flags, usually within a testing environment.

Quick start

SetEnvVar, SetEnvVars and AppendOSArgs all return a single func, which when executed will reset the given variables to their previous state.

Important note - Things may not work as expected if you run your tests in parallel!

Setting environment variables
func TestSomething(t *testing.T) {
    log.Println(os.Getenv("A")) // ""
    
    t.Run("test one", func(t *testing.T) {
        resetEnvVars := tmpenv.SetEnvVars(map[string]string{
            "A":     "123",
        })
        defer resetEnvVars()

        log.Println(os.Getenv("A")) // "123"
    })
    
    log.Println(os.Getenv("A")) // ""
    
    t.Run("test two", func(t *testing.T) {
        resetEnvVars := tmpenv.SetEnvVars(map[string]string{
            "A":     "456",
        })
        defer resetEnvVars()

        log.Println(os.Getenv("A")) // "456"
    })

    log.Println(os.Getenv("A")) // ""
}

Documentation

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func AppendOSArgs

func AppendOSArgs(args ...string) func()

AppendOSArgs will append os.Args with the given values. You can reset the args back to their previous value by executing the returned function.

func SetEnvVar

func SetEnvVar(name string, value string) func()

SetEnvVar will set the given environment variable value. You can reset the env var back to it's previous value by executing the returned function.

Example
package main

import (
	"fmt"
	"github.com/tomwright/tmpenv"
	"os"
)

func main() {
	fmt.Println(os.Getenv("XYZ")) // ""

	reset := tmpenv.SetEnvVar("XYZ", "123")

	// Start tests that depend on XYZ
	fmt.Println(os.Getenv("XYZ")) // "123"
	// Stop tests that depend on XYZ

	reset()

	fmt.Println(os.Getenv("XYZ")) // ""

}
Output:


123

func SetEnvVars

func SetEnvVars(envVars map[string]string) func()

SetEnvVars will set the given environment variables values. You can reset the env vars back to their previous value by executing the returned function.

Types

This section is empty.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL