Skip to content

Commit

Permalink
login tests implemented
Browse files Browse the repository at this point in the history
minor tweaks
  • Loading branch information
Supreeth Basabattini committed Sep 8, 2021
1 parent 6dc238f commit 71e653a
Show file tree
Hide file tree
Showing 7 changed files with 318 additions and 16 deletions.
2 changes: 1 addition & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -11,4 +11,4 @@
# Output of the go coverage tool, specifically when used with LiteIDE
*.out

# Dependency directories (remove the comment below to include it)
/pdcli
2 changes: 2 additions & 0 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -4,5 +4,7 @@ go 1.15

require (
github.com/PagerDuty/go-pagerduty v1.4.1
github.com/onsi/ginkgo v1.16.4
github.com/onsi/gomega v1.16.0
github.com/spf13/cobra v1.2.1
)
41 changes: 41 additions & 0 deletions go.sum

Large diffs are not rendered by default.

6 changes: 6 additions & 0 deletions pkg/config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,12 @@ type Config struct {
// Find returns the pdcli configuration filepath.
// If the config filepath doesn't exist, the desired config filepath string is created and returned.
func Find() (string, error) {

// return the test configuration filepath
if pdcliConfig := os.Getenv("PDCLI_CONFIG"); pdcliConfig != "" {
return pdcliConfig, nil
}

// locate the standard configuration directory
configDir, err := os.UserConfigDir()

Expand Down
1 change: 1 addition & 0 deletions pkg/constants/constants.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,4 +4,5 @@ const (
ConfigFilepath = "pagerduty-cli/config.json"
APIKeyURL = "https://support.pagerduty.com/docs/generating-api-keys#section-generating-a-general-access-rest-api-key"
APIKeyRegex = "^[a-z|A-Z0-9+_-]{20}$"
SampleKey = "y_NbAkKc66ryYTWUXYEu"
)
74 changes: 59 additions & 15 deletions tests/login_test.go
Original file line number Diff line number Diff line change
@@ -1,22 +1,66 @@
package main
package tests

import (
"testing"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
"github.com/openshift/pagerduty-short-circuiter/pkg/constants"
)

func TestPdcli(t *testing.T) {
var _ = Describe("pdcli login", func() {

assertCorrectMessage := func(t testing.TB, actual, expected int) {
t.Helper()
if actual != expected {
t.Errorf("Actual:%d Expected:%d", actual, expected)
}
}
var jsonTemplate string

//Tesing all the functions against an empty file.
t.Run("sample test", func(t *testing.T) {
actual := 1
expected := 1
assertCorrectMessage(t, actual, expected)
BeforeEach(func() {
jsonTemplate = `{
"api_key" : "` + constants.SampleKey + `"
}`

})

When("the login command is run", func() {
It("creates a configuration file", func() {
result := NewCommand().
Args(
"login",
).
GetStdIn(constants.SampleKey + "\n").
Run()

Expect(result.ConfigFile()).ToNot(BeEmpty())
Expect(result.ConfigString()).To(MatchJSON(jsonTemplate))
})
})

When("the login command is run with the 'api-key' option", func() {
It("creates a configuration file", func() {

result := NewCommand().
Args(
"login",
"--api-key",
constants.SampleKey,
).
Run()

Expect(result.ConfigFile()).ToNot(BeEmpty())
Expect(result.ConfigString()).To(MatchJSON(jsonTemplate))
})
})

When("the login command is run", func() {
It("the sample key is used against PagerDuty REST API", func() {

result := NewCommand().
Args(
"login",
"--api-key",
constants.SampleKey,
).
Run()

Expect(result.ConfigFile()).ToNot(BeEmpty())
Expect(result.ExitCode()).ToNot(BeZero())
Expect(result.ErrString()).To(ContainSubstring("Unauthorized"))
})
})
}
})
208 changes: 208 additions & 0 deletions tests/main_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,208 @@
package tests

import (
"bytes"
"errors"
"io/ioutil"
"os"
"os/exec"
"path/filepath"
"runtime"
"strings"
"testing"

. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
)

func TestPDCLI(t *testing.T) {
RegisterFailHandler(Fail)
RunSpecs(t, "PDCLI Test Suite")
}

var executable string

var _ = BeforeSuite(func() {
executableName := "pdcli"

if runtime.GOOS == "windows" {
executableName += ".exe"
}

executable = filepath.Join("..", executableName)

// Create the PDCLI binary in the project root directory
cmd := exec.Command("go", "build", "-o", executable, "../cmd/pdcli")
err := cmd.Run()

Expect(err).ToNot(HaveOccurred(), "Error creating binary file for test suite", executable)
})

type TestCommand struct {
args []string
config string
env map[string]string
input []byte
}

// TestResult contains the result of the CLI command executed.
type TestResult struct {
configFile string
configData []byte
out []byte
err []byte
exitCode int
}

// NewCommand creates a new CLI command runner.
func NewCommand() *TestCommand {
return &TestCommand{
env: map[string]string{},
}
}

// GetStdIn gets the standard input for the CLI command.
func (tc *TestCommand) GetStdIn(value string) *TestCommand {
tc.input = []byte(value)
return tc
}

// Env sets an environment variable to the CLI command.
func (tc *TestCommand) Env(name, value string) *TestCommand {
tc.env[name] = value
return tc
}

// Args adds a set of arguments to the command.
func (tc *TestCommand) Args(values ...string) *TestCommand {
tc.args = append(tc.args, values...)
return tc
}

// ConfigFile returns the name of the temporary configuration file.
// It will return an empty string if the confif file doesn't exist.
func (tr *TestResult) ConfigFile() string {
return tr.configFile
}

// ConfigString returns the content of the configuration file.
func (tr *TestResult) ConfigString() string {
return string(tr.configData)
}

// Err returns the standard errour output of the test command.
func (tr *TestResult) ErrString() string {
return string(tr.err)
}

// ExitCode returns the exit code of the test command.
func (tr *TestResult) ExitCode() int {
return tr.exitCode
}

func (tc *TestCommand) Run() *TestResult {
var err error

// Create a temporary config directory
tmpDir, err := ioutil.TempDir("", "pdcli-test-*.d")

ExpectWithOffset(1, err).ToNot(HaveOccurred())

// Delete the temp dir after test suite is finished
defer func() {
err = os.RemoveAll(tmpDir)
ExpectWithOffset(1, err).ToNot(HaveOccurred())
}()

// Create a temporary configuration file
configFile := filepath.Join(tmpDir, "config.json")

if tc.config != "" {
err = ioutil.WriteFile(configFile, []byte(tc.config), 0600)
ExpectWithOffset(1, err).ToNot(HaveOccurred())
}

// Parse the current environment into a map
envMap := map[string]string{}
for _, text := range os.Environ() {
index := strings.Index(text, "=")
var name string
var value string
if index > 0 {
name = text[0:index]
value = text[index+1:]
} else {
name = text
value = ""
}
envMap[name] = value
}

// Add the environment variables
for name, value := range tc.env {
envMap[name] = value
}

// Add to the environment the variable that points to a configuration file
envMap["PDCLI_CONFIG"] = configFile

// Reconstruct the environment list
envList := make([]string, 0, len(envMap))

for name, value := range envMap {
envList = append(envList, name+"="+value)
}

// Create the buffers
inBuf := &bytes.Buffer{}

// if standard input is provided
if tc.input != nil {
inBuf.Write(tc.input)
}

outBuf := &bytes.Buffer{}
errBuf := &bytes.Buffer{}

// Create the pdcli command
cmd := exec.Command(executable, tc.args...)
cmd.Env = envList
cmd.Stdin = inBuf
cmd.Stdout = outBuf
cmd.Stderr = errBuf

// Run the command
err = cmd.Run()

// Check if the configuration file exists
_, err = os.Stat(configFile)

if errors.Is(err, os.ErrNotExist) {
configFile = ""
} else if err != nil {
Expect(err).ToNot(HaveOccurred())
}

var configData []byte

if configFile != "" {
configData, err = ioutil.ReadFile(configFile)
Expect(err).ToNot(HaveOccurred())
}

// The result rendered from the test command
result := &TestResult{
configFile: configFile,
configData: configData,
out: outBuf.Bytes(),
err: errBuf.Bytes(),
exitCode: cmd.ProcessState.ExitCode(),
}

return result
}

var _ = AfterSuite(func() {
err := os.Remove("../pdcli")
Expect(err).ToNot(HaveOccurred())
})

0 comments on commit 71e653a

Please sign in to comment.