Skip to content

Commit

Permalink
add some tests
Browse files Browse the repository at this point in the history
  • Loading branch information
hehu80 committed Sep 13, 2024
1 parent d32623a commit 43cad6b
Show file tree
Hide file tree
Showing 15 changed files with 302 additions and 41 deletions.
2 changes: 1 addition & 1 deletion .github/workflows/test.yml
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ jobs:
run: go build ./...

- name: Run tests
run: go test ./... -json > TestResults-.json
run: go test ./... -json > TestResults.json

- name: Upload test results
uses: actions/upload-artifact@v4
Expand Down
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1 +1,3 @@
/*.csv
/.idea/
/*.iml
8 changes: 4 additions & 4 deletions cmd/server/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,8 @@ package main
import (
"air-pollution-service/config"
"air-pollution-service/internal/csv"
"air-pollution-service/internal/repository"
"air-pollution-service/internal/resource"
"air-pollution-service/internal/store"
"flag"
"fmt"
"github.com/go-chi/chi/v5"
Expand All @@ -17,7 +17,7 @@ import (
func main() {
c := config.New()

repo, err := repository.New(csv.New(c.AirPollutionFile))
repo, err := store.New(csv.New(c.AirPollutionFile))
if err != nil {
log.Panic(err)
}
Expand All @@ -32,8 +32,8 @@ func main() {
r.Use(middleware.URLFormat)
r.Use(render.SetContentType(render.ContentTypeJSON))

r.Mount("/countries", resource.CountryResource{Repository: repo}.Routes())
r.Mount("/emissions", resource.EmissionResource{Repository: repo}.Routes())
r.Mount("/countries", resource.CountryResource{Storage: repo}.Routes())
r.Mount("/emissions", resource.EmissionResource{Storage: repo}.Routes())

err = http.ListenAndServe(fmt.Sprintf(":%d", c.Server.Port), r)
if err != nil {
Expand Down
2 changes: 1 addition & 1 deletion cmd/server/main_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,5 +3,5 @@ package main
import "testing"

func TestMain(m *testing.M) {
// TODO
// TODO add tests
}
12 changes: 10 additions & 2 deletions go.mod
Original file line number Diff line number Diff line change
@@ -1,13 +1,21 @@
module air-pollution-service

go 1.22
go 1.22.0

toolchain go1.22.5

require (
github.com/go-chi/chi/v5 v5.1.0
github.com/go-chi/render v1.0.3
github.com/gocarina/gocsv v0.0.0-20240520201108-78e41c74b4b1
github.com/joeshaw/envdecode v0.0.0-20200121155833-099f1fc765bd
github.com/montanaflynn/stats v0.7.1
github.com/stretchr/testify v1.9.0
)

require github.com/ajg/form v1.5.1 // indirect
require (
github.com/ajg/form v1.5.1 // indirect
github.com/davecgh/go-spew v1.1.1 // indirect
github.com/pmezard/go-difflib v1.0.0 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect
)
22 changes: 22 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
github.com/ajg/form v1.5.1 h1:t9c7v8JUKu/XxOGBU0yjNpaMloxGEJhUkqFRq0ibGeU=
github.com/ajg/form v1.5.1/go.mod h1:uL1WgH+h2mgNtvBq0339dVnzXdBETtL2LeUXaIv25UY=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/go-chi/chi/v5 v5.1.0 h1:acVI1TYaD+hhedDJ3r54HyA6sExp3HfXq7QWEEY/xMw=
github.com/go-chi/chi/v5 v5.1.0/go.mod h1:DslCQbL2OYiznFReuXYUmQ2hGd1aDpCnlMNITLSKoi8=
github.com/go-chi/render v1.0.3 h1:AsXqd2a1/INaIfUSKq3G5uA8weYx20FOsM7uSoCyyt4=
github.com/go-chi/render v1.0.3/go.mod h1:/gr3hVkmYR0YlEy3LxCuVRFzEu9Ruok+gFqbIofjao0=
github.com/gocarina/gocsv v0.0.0-20240520201108-78e41c74b4b1 h1:FWNFq4fM1wPfcK40yHE5UO3RUdSNPaBC+j3PokzA6OQ=
github.com/gocarina/gocsv v0.0.0-20240520201108-78e41c74b4b1/go.mod h1:5YoVOkjYAQumqlV356Hj3xeYh4BdZuLE0/nRkf2NKkI=
github.com/joeshaw/envdecode v0.0.0-20200121155833-099f1fc765bd h1:nIzoSW6OhhppWLm4yqBwZsKJlAayUu5FGozhrF3ETSM=
github.com/joeshaw/envdecode v0.0.0-20200121155833-099f1fc765bd/go.mod h1:MEQrHur0g8VplbLOv5vXmDzacSaH9Z7XhcgsSh1xciU=
github.com/montanaflynn/stats v0.7.1 h1:etflOAAHORrCC44V+aR6Ftzort912ZU+YLiSTuV8eaE=
github.com/montanaflynn/stats v0.7.1/go.mod h1:etXPPgVO6n31NxCd9KQUMvCM+ve0ruNzt6R8Bnaayow=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/stretchr/testify v1.9.0 h1:HtqpIVDClZ4nwg75+f6Lvsy/wHu+3BoSGCbBAcpTsTg=
github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
14 changes: 13 additions & 1 deletion http-request-emissions.http
Original file line number Diff line number Diff line change
Expand Up @@ -28,4 +28,16 @@ GET {{url}}:{{port}}/emissions/year/
# }
# ...
# }
GET {{url}}:{{port}}/emissions/country/
GET {{url}}:{{port}}/emissions/country/

### GET all emissions of a single country
# expected response:
# {
# "nox_emissions": {
# "average": 1597043.105081651,
# "median": 71152.08,
# "standard_deviation": 8007847.335584437
# },
# ...
# }
GET {{url}}:{{port}}/emissions/country/Germany
2 changes: 1 addition & 1 deletion internal/csv/csv_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,5 +3,5 @@ package csv
import "testing"

func TestCSV(t *testing.T) {
// TODO
// TODO add tests
}
8 changes: 4 additions & 4 deletions internal/resource/countries.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,15 @@ package resource

import (
"air-pollution-service/internal/model"
"air-pollution-service/internal/repository"
"air-pollution-service/internal/store"
"fmt"
"github.com/go-chi/chi/v5"
"github.com/go-chi/render"
"net/http"
)

type CountryResource struct {
*repository.Repository
Storage store.Storage
}

type countryResponse struct {
Expand Down Expand Up @@ -42,7 +42,7 @@ func (rs CountryResource) Routes() chi.Router {
}

func (rs CountryResource) List(w http.ResponseWriter, r *http.Request) {
countries := rs.Repository.GetCountries()
countries := rs.Storage.GetCountries()
if countries == nil {
if err := render.Render(w, r, ErrRender(fmt.Sprintf("No country found"), 404)); err != nil {
render.Status(r, 500)
Expand Down Expand Up @@ -71,7 +71,7 @@ func (rs CountryResource) Get(w http.ResponseWriter, r *http.Request) {
return
}

country := rs.Repository.GetCountry(name)
country := rs.Storage.GetCountry(name)
if country == nil {
if err := render.Render(w, r, ErrRender(fmt.Sprintf("No country with name %s found", name), 404)); err != nil {
render.Status(r, 500)
Expand Down
80 changes: 77 additions & 3 deletions internal/resource/countries_test.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,81 @@
package resource

import "testing"
import (
"air-pollution-service/internal/model"
"context"
"encoding/json"
"github.com/go-chi/chi/v5"
"github.com/stretchr/testify/assert"
"io/ioutil"
"net/http"
"net/http/httptest"
"testing"
)

func TestCountries(t *testing.T) {
// TODO
type fakeCountryStorage struct {
countries []*model.Country
}

func (s fakeCountryStorage) FindAllByYears() map[int][]*model.Emissions {
return nil
}

func (s fakeCountryStorage) FindAllByCountries() map[string][]*model.Emissions {
return nil
}

func (s fakeCountryStorage) FindAllByCountry(name string) map[int]*model.Emissions {
return nil
}

func (s fakeCountryStorage) GetCountry(name string) *model.Country {
if len(s.countries) == 0 {
return nil
}
return s.countries[0]
}

func (s fakeCountryStorage) GetCountries() []*model.Country {
return s.countries
}

func TestCountriesGetNonExisting(t *testing.T) {
w := httptest.NewRecorder()
req := httptest.NewRequest(http.MethodGet, "/", nil)
ctx := chi.NewRouteContext()
req = req.WithContext(context.WithValue(req.Context(), chi.RouteCtxKey, ctx))
ctx.URLParams.Add("name", "Schlaraffenland")
countryHandler := CountryResource{Storage: fakeCountryStorage{[]*model.Country{}}}

countryHandler.Get(w, req)
res := w.Result()
defer res.Body.Close()
_, err := ioutil.ReadAll(res.Body)
assert.Nil(t, err)
assert.Equal(t, 404, res.StatusCode)
}

func TestCountriesGetExisting(t *testing.T) {
w := httptest.NewRecorder()
req := httptest.NewRequest(http.MethodGet, "/", nil)
ctx := chi.NewRouteContext()
req = req.WithContext(context.WithValue(req.Context(), chi.RouteCtxKey, ctx))
ctx.URLParams.Add("name", "Schlaraffenland")
countryHandler := CountryResource{Storage: fakeCountryStorage{[]*model.Country{{
Name: "Schlaraffenland",
Code: "SCH",
}}}}

countryHandler.Get(w, req)
res := w.Result()
defer res.Body.Close()
data, err := ioutil.ReadAll(res.Body)
assert.Nil(t, err)
assert.Equal(t, 200, res.StatusCode)

country := countryResponse{}
err = json.Unmarshal(data, &country)
assert.Nil(t, err)
assert.Equal(t, "Schlaraffenland", country.Name)
assert.Equal(t, "SCH", country.Code)
}
30 changes: 26 additions & 4 deletions internal/resource/emissions.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,16 +2,17 @@ package resource

import (
"air-pollution-service/internal/model"
"air-pollution-service/internal/repository"
"air-pollution-service/internal/store"
"encoding/json"
"fmt"
"github.com/go-chi/chi/v5"
"github.com/go-chi/render"
"github.com/montanaflynn/stats"
"net/http"
)

type EmissionResource struct {
*repository.Repository
Storage store.Storage
}

type airPollutionResponse struct {
Expand Down Expand Up @@ -89,14 +90,15 @@ func (rs EmissionResource) Routes() chi.Router {

r.Route("/country/", func(r chi.Router) {
r.Get("/", rs.ListByCountry)
r.Get("/{name}", rs.GetByCountry)
})

return r
}

func (rs EmissionResource) ListByYear(w http.ResponseWriter, r *http.Request) {
response := make(map[int]airPollutionEmissionsResponse)
for year, emissions := range rs.FindAllByYears() {
for year, emissions := range rs.Storage.FindAllByYears() {
response[year] = newAirPollutionEmissionsResponse(emissions)
}

Expand All @@ -108,7 +110,7 @@ func (rs EmissionResource) ListByYear(w http.ResponseWriter, r *http.Request) {

func (rs EmissionResource) ListByCountry(w http.ResponseWriter, r *http.Request) {
response := make(map[string]airPollutionEmissionsResponse)
for country, emissions := range rs.FindAllByCountries() {
for country, emissions := range rs.Storage.FindAllByCountries() {
response[country] = newAirPollutionEmissionsResponse(emissions)
}

Expand All @@ -117,3 +119,23 @@ func (rs EmissionResource) ListByCountry(w http.ResponseWriter, r *http.Request)
render.Status(r, 500)
}
}

func (rs EmissionResource) GetByCountry(w http.ResponseWriter, r *http.Request) {
name := chi.URLParam(r, "name")
if name == "" {
if err := render.Render(w, r, ErrRender(fmt.Sprintf("Country name missing"), 400)); err != nil {
render.Status(r, 500)
}
return
}

var countryEmissions []*model.Emissions
for _, emissions := range rs.Storage.FindAllByCountry(name) {
countryEmissions = append(countryEmissions, emissions)
}

response := newAirPollutionEmissionsResponse(countryEmissions)
if err := render.Render(w, r, response); err != nil {
render.Status(r, 500)
}
}
Loading

0 comments on commit 43cad6b

Please sign in to comment.