Skip to content

Commit

Permalink
test: add tests for seed and check commands
Browse files Browse the repository at this point in the history
  • Loading branch information
Michad committed Jun 27, 2024
1 parent cf9deb7 commit 01c9f60
Show file tree
Hide file tree
Showing 8 changed files with 332 additions and 12 deletions.
23 changes: 13 additions & 10 deletions cmd/check.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ package cmd

import (
"encoding/json"
"os"
"fmt"

"github.com/spf13/cobra"
)
Expand All @@ -26,21 +26,24 @@ var checkCmd = &cobra.Command{
Short: "Validates your configuration",
Long: `Checks the validity of the configuration you supplied and then exits. If everything is valid the program displays "Valid" and exits with a code of 0. If the configuration is invalid then a descriptive error is outputted and it exits with a non-zero status code.`,
Run: func(cmd *cobra.Command, args []string) {
verbose, _ := cmd.Flags().GetBool("verbose")
echo, _ := cmd.Flags().GetBool("echo")
out := cmd.OutOrStdout()

cfg, _, _, err := parseConfigIntoStructs(cmd)

if cfg != nil && verbose {
enc := json.NewEncoder(os.Stdout)
enc.SetIndent(" ", " ")
enc.Encode(cfg)
}

if err != nil {
panic(err)
fmt.Fprintf(out, "Invalid configuration: %v\n", err.Error())
exit(1)
return
}

println("Valid")
if cfg != nil && echo {
enc := json.NewEncoder(out)
enc.SetIndent(" ", " ")
enc.Encode(cfg)
} else {
fmt.Fprintln(out, "Valid")
}
},
}

Expand Down
194 changes: 194 additions & 0 deletions cmd/check_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,194 @@
// Copyright 2024 Michael Davis
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package cmd

import (
"bytes"
"encoding/json"
"fmt"
"io"
"testing"

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

func Test_CheckCommand_Execute(t *testing.T) {
exitStatus = -1
rootCmd.ResetFlags()
checkCmd.ResetFlags()
initRoot()
initCheck()

b := bytes.NewBufferString("")
rootCmd.SetOutput(b)
rootCmd.SetArgs([]string{"config", "check", "-c", "../examples/configurations/simple.json"})
assert.Nil(t, rootCmd.Execute())
out, err := io.ReadAll(b)
if err != nil {
t.Fatal(err)
}

assert.Equal(t, "Valid\n", string(out))
assert.Equal(t, -1, exitStatus)
}

func Test_CheckCommand_ExecuteInline(t *testing.T) {
exitStatus = -1
rootCmd.ResetFlags()
checkCmd.ResetFlags()
initRoot()
initCheck()

b := bytes.NewBufferString("")
rootCmd.SetOutput(b)

cfg := `cache:
name: multi
tiers:
- name: memory
maxsize: 100
ttl: 1000
- name: disk
path: /tmp
layers:
- id: osm
provider:
name: proxy
url: https://tile.openstreetmap.org/{z}/{x}/{y}.png
`
rootCmd.SetArgs([]string{"config", "check", "--raw-config", cfg})
assert.Nil(t, rootCmd.Execute())
out, err := io.ReadAll(b)
if err != nil {
t.Fatal(err)
}

assert.Equal(t, "Valid\n", string(out))
assert.Equal(t, -1, exitStatus)
}
func Test_CheckCommand_ExecuteInlineJson(t *testing.T) {
exitStatus = -1
rootCmd.ResetFlags()
checkCmd.ResetFlags()
initRoot()
initCheck()

b := bytes.NewBufferString("")
rootCmd.SetOutput(b)

cfg := `
{
"cache": {
"name": "none"
},
"layers": [
{
"id": "osm",
"provider": {
"name": "proxy",
"url": "https://tile.openstreetmap.org/{z}/{x}/{y}.png"
}
}
]
}
`
rootCmd.SetArgs([]string{"config", "check", "--raw-config", cfg})
assert.Nil(t, rootCmd.Execute())
out, err := io.ReadAll(b)
if err != nil {
t.Fatal(err)
}

assert.Equal(t, "Valid\n", string(out))
assert.Equal(t, -1, exitStatus)
}

func Test_CheckCommand_ExecuteCompare(t *testing.T) {
exitStatus = -1
rootCmd.ResetFlags()
checkCmd.ResetFlags()
initRoot()
initCheck()

b := bytes.NewBufferString("")
rootCmd.SetOutput(b)

cfg := `cache:
name: multi
tiers:
- name: memory
maxsize: 100
ttl: 1000
- name: disk
path: /tmp
layers:
- id: osm
provider:
name: proxy
url: https://tile.openstreetmap.org/{z}/{x}/{y}.png
`
rootCmd.SetArgs([]string{"config", "check", "--raw-config", cfg, "--echo"})
assert.Nil(t, rootCmd.Execute())
out, err := io.ReadAll(b)
if err != nil {
t.Fatal(err)
}

assert.Equal(t, -1, exitStatus)

fmt.Println(string(out))

var echoed map[string]interface{}
json.Unmarshal(out, &echoed)

assert.Equal(t, "multi", echoed["Cache"].(map[string]interface{})["name"])
assert.Equal(t, "osm", echoed["Layers"].([]interface{})[0].(map[string]interface{})["Id"])
}

func Test_CheckCommand_Invalid(t *testing.T) {
exitStatus = -1
rootCmd.ResetFlags()
checkCmd.ResetFlags()
initRoot()
initCheck()

b := bytes.NewBufferString("")
rootCmd.SetOutput(b)
cfg := `cache:
name: multi
tiers:
- name: memory
maxsize: 100
ttl: 1000
- name: disk
path: %v
OMG THIS ISN'T VALID!
layers:
- id: osm
provider:
name: proxy
url: https://tile.openstreetmap.org/{z}/{x}/{y}.png
`

rootCmd.SetArgs([]string{"config", "check", "--raw-config", cfg})
assert.Nil(t, rootCmd.Execute())
out, err := io.ReadAll(b)
if err != nil {
t.Fatal(err)
}

assert.NotEqual(t, "Valid\n", string(out))
assert.Equal(t, 1, exitStatus)
}
2 changes: 1 addition & 1 deletion cmd/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ func init() {

func initRoot() {
rootCmd.PersistentFlags().StringP("config", "c", "./tilegroxy.yml", "A file path to the configuration file to use. The file should have an extension of either json or yml/yaml and be readable.")
rootCmd.PersistentFlags().String("raw-config", "", "The full configuration to be used.")
rootCmd.PersistentFlags().String("raw-config", "", "The full configuration to be used as JSON.")
rootCmd.MarkFlagsMutuallyExclusive("config", "raw-config")
}

Expand Down
7 changes: 7 additions & 0 deletions cmd/seed.go
Original file line number Diff line number Diff line change
Expand Up @@ -51,13 +51,15 @@ Example:
if err := errors.Join(err1, err2, err3, err4, err5, err6, err7, err8, err9); err != nil {
fmt.Fprintf(out, "Error: %v", err)
exit(1)
return
}

_, layerObjects, _, err := parseConfigIntoStructs(cmd)

if err != nil {
fmt.Fprintf(out, "Error: %v", err)
exit(1)
return
}

var layer *layers.Layer
Expand All @@ -71,11 +73,13 @@ Example:
if layer == nil {
fmt.Fprintln(out, "Error: Invalid layer")
exit(1)
return
}

if numThread == 0 {
fmt.Fprintln(out, "Error: threads cannot be 0")
exit(1)
return
}

b := internal.Bounds{South: float64(minLat), West: float64(minLon), North: float64(maxLat), East: float64(maxLon)}
Expand All @@ -86,19 +90,22 @@ Example:
if z > internal.MaxZoom {
fmt.Fprintf(out, "Error: zoom must be less than %v\n", internal.MaxZoom)
exit(1)
return
}
newTiles, err := b.FindTiles(layerName, uint(z), force)

if err != nil {
fmt.Fprintf(out, "Error: %v\n", err.Error())
exit(1)
return
}

tileRequests = append(tileRequests, (*newTiles)...)

if len(tileRequests) > 10000 && !force {
fmt.Fprintln(out, "Too many tiles to seed. Run with --force if you're sure you want to generate this many tiles")
exit(1)
return
}
}

Expand Down
Loading

0 comments on commit 01c9f60

Please sign in to comment.