Skip to content

Commit

Permalink
config: not properly loaded error (#140)
Browse files Browse the repository at this point in the history
* config: not properly loaded error

When a wrong config file was used, it result in a panic.
Adding some check condition to validate the Unmarshaled configuration
before using it

fixes #134

* check if datasource is set

* move error locally instead of utils/errors
  • Loading branch information
JG² authored and Quentin-M committed Apr 18, 2016
1 parent 8d5a330 commit af2c688
Show file tree
Hide file tree
Showing 2 changed files with 90 additions and 0 deletions.
9 changes: 9 additions & 0 deletions config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
package config

import (
"errors"
"io/ioutil"
"os"
"time"
Expand All @@ -23,6 +24,9 @@ import (
"gopkg.in/yaml.v2"
)

// ErrDatasourceNotLoaded is returned when the datasource variable in the configuration file is not loaded properly
var ErrDatasourceNotLoaded = errors.New("could not load configuration: no database source specified")

// File represents a YAML configuration file that namespaces all Clair
// configuration under the top-level "clair" key.
type File struct {
Expand Down Expand Up @@ -112,6 +116,11 @@ func Load(path string) (config *Config, err error) {
}
config = &cfgFile.Clair

if config.Database.Source == "" {
err = ErrDatasourceNotLoaded
return
}

// Generate a pagination key if none is provided.
if config.API.PaginationKey == "" {
var key fernet.Key
Expand Down
81 changes: 81 additions & 0 deletions config/config_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
package config

import (
"io/ioutil"
"log"
"os"
"testing"

"github.com/stretchr/testify/assert"
)

const wrongConfig = `
dummyKey:
wrong:true
`

const goodConfig = `
clair:
database:
source: postgresql://postgres:root@postgres:5432?sslmode=disable
cacheSize: 16384
api:
port: 6060
healthport: 6061
timeout: 900s
paginationKey:
servername:
cafile:
keyfile:
certfile:
updater:
interval: 2h
notifier:
attempts: 3
renotifyInterval: 2h
http:
endpoint:
servername:
cafile:
keyfile:
certfile:
proxy:
`

func TestLoadWrongConfiguration(t *testing.T) {
tmpfile, err := ioutil.TempFile("", "clair-config")
if err != nil {
log.Fatal(err)
}

defer os.Remove(tmpfile.Name()) // clean up
if _, err := tmpfile.Write([]byte(wrongConfig)); err != nil {
log.Fatal(err)
}
if err := tmpfile.Close(); err != nil {
log.Fatal(err)
}

_, err = Load(tmpfile.Name())

assert.EqualError(t, err, ErrDatasourceNotLoaded.Error())
}

func TestLoad(t *testing.T) {
tmpfile, err := ioutil.TempFile("", "clair-config")
if err != nil {
log.Fatal(err)
}

defer os.Remove(tmpfile.Name()) // clean up

if _, err := tmpfile.Write([]byte(goodConfig)); err != nil {
log.Fatal(err)
}
if err := tmpfile.Close(); err != nil {
log.Fatal(err)
}

_, err = Load(tmpfile.Name())
assert.NoError(t, err)
}

0 comments on commit af2c688

Please sign in to comment.