Skip to content

Commit

Permalink
Add unit tests for sourcing behavior
Browse files Browse the repository at this point in the history
  • Loading branch information
m90 committed Feb 19, 2024
1 parent 00838ba commit 0de1d73
Show file tree
Hide file tree
Showing 6 changed files with 98 additions and 0 deletions.
21 changes: 21 additions & 0 deletions .github/workflows/unit.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
name: Run Unit Tests

on:
push:
branches:
- main
pull_request:

jobs:
build:
runs-on: ubuntu-22.04
steps:
- uses: actions/checkout@v4
- name: Setup Go
uses: actions/setup-go@v4
with:
go-version: '1.22.x'
- name: Install dependencies
run: go get .
- name: Test with the Go CLI
run: go test -v ./...
2 changes: 2 additions & 0 deletions cmd/backup/config_provider.go
Original file line number Diff line number Diff line change
Expand Up @@ -123,6 +123,8 @@ func loadConfigsFromEnvFiles(directory string) ([]*Config, error) {
return configs, nil
}

// source tries to mimic the pre v2.37.0 behavior of calling
// `set +a; source $path; set -a` and returns the env vars as a map
func source(path string) (map[string]string, error) {
f, err := os.Open(path)
if err != nil {
Expand Down
67 changes: 67 additions & 0 deletions cmd/backup/config_provider_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
package main

import (
"os"
"reflect"
"testing"
)

func TestSource(t *testing.T) {
tests := []struct {
name string
input string
expectError bool
expectedOutput map[string]string
}{
{
"default",
"testdata/default.env",
false,
map[string]string{
"FOO": "bar",
"BAZ": "qux",
},
},
{
"not found",
"testdata/nope.env",
true,
nil,
},
{
"braces",
"testdata/braces.env",
false,
map[string]string{
"FOO": "${bar:-qux}",
"BAR": "xxx",
},
},
{
"expansion",
"testdata/expansion.env",
false,
map[string]string{
"BAR": "xxx",
"FOO": "xxx",
"BAZ": "xxx",
"QUX": "yyy",
},
},
}

os.Setenv("QUX", "yyy")
defer os.Unsetenv("QUX")

for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
result, err := source(test.input)
if (err != nil) != test.expectError {
t.Errorf("Unexpected error value %v", err)
}
if !reflect.DeepEqual(test.expectedOutput, result) {
t.Errorf("Expected %v, got %v", test.expectedOutput, result)
}
})
}
}
2 changes: 2 additions & 0 deletions cmd/backup/testdata/braces.env
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
FOO=${bar:-qux}
BAR=xxx
2 changes: 2 additions & 0 deletions cmd/backup/testdata/default.env
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
FOO=bar
BAZ=qux
4 changes: 4 additions & 0 deletions cmd/backup/testdata/expansion.env
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
BAR=xxx
FOO=${BAR}
BAZ=$BAR
QUX=${QUX}

0 comments on commit 0de1d73

Please sign in to comment.