Skip to content

Commit

Permalink
add documentation;add test tools
Browse files Browse the repository at this point in the history
  • Loading branch information
olivierdelobre committed Feb 21, 2024
1 parent 00f5ef4 commit 4d9edde
Show file tree
Hide file tree
Showing 6 changed files with 194 additions and 3 deletions.
56 changes: 55 additions & 1 deletion api/api.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,9 @@ import (
api "github.com/epfl-si/go-toolbox/api/models"
)

// CallApi calls the API with the specified HTTP verb, URL, payload, user ID, and password.
//
// It returns a pointer to http.Response and an error.
func CallApi(verb string, url string, payload string, userId string, password string) (*http.Response, error) {
if os.Getenv("API_USERID") == "" || os.Getenv("API_USERPWD") == "" {
return nil, fmt.Errorf("missing API_USERID or API_USERPWD environment variable")
Expand Down Expand Up @@ -43,6 +46,9 @@ func CallApi(verb string, url string, payload string, userId string, password st
return resp, nil
}

// GetPerson retrieves a person by their ID.
//
// It takes a string parameter persId and returns a pointer to api.Person, an int, and an error.
func GetPerson(persId string) (*api.Person, int, error) {
err := checkEnvironment()
if err != nil {
Expand All @@ -69,6 +75,10 @@ func GetPerson(persId string) (*api.Person, int, error) {
return &entity, res.StatusCode, nil
}

// GetUnit retrieves a unit by its ID.
//
// unitId string - the ID of the unit to retrieve.
// *api.Unit, int, error - returns the unit, status code, and any error encountered.
func GetUnit(unitId string) (*api.Unit, int, error) {
err := checkEnvironment()
if err != nil {
Expand All @@ -95,7 +105,10 @@ func GetUnit(unitId string) (*api.Unit, int, error) {
return &entity, res.StatusCode, nil
}

// accredId is persId:unitId
// GetAccred retrieves an Accred from the API.
//
// accredId is a string formated like persId:unitId
// *api.Accred, int, error
func GetAccred(accredId string) (*api.Accred, int, error) {
err := checkEnvironment()
if err != nil {
Expand Down Expand Up @@ -127,6 +140,17 @@ type AccredsResponse struct {
Count int64 `json:"count"`
}

// GetAccreds retrieves accreditations for the given persons and unit IDs.
//
// Parameters:
// - persIds string: the person IDs (scipers separated by a comma)
// - unitIds string: the unit IDs (unit IDs separated by a comma)
//
// Return type(s):
// - []*api.Accred: slice of accreditations
// - int64: count of accreditations
// - int: response http status code
// - error: any error that occurred
func GetAccreds(persIds string, unitIds string) ([]*api.Accred, int64, int, error) {
err := checkEnvironment()
if err != nil {
Expand All @@ -153,6 +177,10 @@ func GetAccreds(persIds string, unitIds string) ([]*api.Accred, int64, int, erro
return entities.Accreds, entities.Count, res.StatusCode, nil
}

// GetAccredsFromUrl retrieves accreditations from the given URL.
//
// url: the URL to retrieve accreditations from.
// []*api.Accred, int64, int, error: returns a slice of accreditations, total count, response status code, and any error encountered.
func GetAccredsFromUrl(url string) ([]*api.Accred, int64, int, error) {
res, err := CallApi("GET", url, "", os.Getenv("API_USERID"), os.Getenv("API_USERPWD"))
if err != nil {
Expand All @@ -179,6 +207,19 @@ type AuthorizationsResponse struct {
Count int64 `json:"count"`
}

// GetAuthorizations retrieves authorizations based on provided parameters.
//
// Parameters:
// - persIds string: the person IDs (scipers separated by a comma)
// - resIds string: the resource IDs (resource IDs separated by a comma)
// - authType string: the authorization type (right, role, property, status)
// - authIds string: the authorization IDs (authorization IDs or names separated by a comma)
//
// Return type(s):
// []*api.Authorization: slice of authorizations
// int64: count of authorizations
// int: response http status code
// error: any error that occurred
func GetAuthorizations(persIds string, resIds string, authType string, authIds string) ([]*api.Authorization, int64, int, error) {
err := checkEnvironment()
if err != nil {
Expand All @@ -205,6 +246,16 @@ func GetAuthorizations(persIds string, resIds string, authType string, authIds s
return entities.Authorizations, entities.Count, res.StatusCode, nil
}

// GetAuthorizationsFromUrl retrieves authorizations from the given URL.
//
// Parameter(s):
// - url string - the URL to fetch authorizations from
//
// Return type(s):
// - []*api.Authorization: slice of authorizations
// - int64: count of authorizations
// - int: HTTP status code
// - error: any error that occurred during the process
func GetAuthorizationsFromUrl(url string) ([]*api.Authorization, int64, int, error) {
res, err := CallApi("GET", url, "", os.Getenv("API_USERID"), os.Getenv("API_USERPWD"))
if err != nil {
Expand All @@ -226,6 +277,9 @@ func GetAuthorizationsFromUrl(url string) ([]*api.Authorization, int64, int, err
return entities.Authorizations, entities.Count, res.StatusCode, nil
}

// checkEnvironment checks the environment for required variables.
//
// Returns an error if something's wrong
func checkEnvironment() error {
if os.Getenv("API_GATEWAY_URL") == "" {
return fmt.Errorf("missing API_GATEWAY_URL environment variable, possible values are 'https://api-test.epfl.ch', 'https://api-preprod.epfl.ch', 'https://api.epfl.ch'")
Expand Down
17 changes: 16 additions & 1 deletion database/database.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,22 @@ import (
"gorm.io/gorm/logger"
)

// GetGormDB initializes a connection to the database and returns a handle
// GetGormDB returns a Gorm database connection.
//
// Parameters:
// - log *zap.Logger: a logger instance
// - host string: the database host
// - name string: the database name
// - user string: the database user
// - pass string: the database password
// - port string: the database port
// - param string: the specific database parameters
// - maxIdle int: the maximum number of idle connections
// - maxOpen int: the maximum number of open connections
//
// Return type(s):
// - *gorm.DB: the Gorm database connection
// - error: an error, if any, encountered during the connection
func GetGormDB(log *zap.Logger, host, name, user, pass, port, param string, maxIdle int, maxOpen int) (*gorm.DB, error) {
//log.Infof("[GetGormDB] Connecting to 'database' %s on host %s as user '%s' (%s)", name, host, user, param)
logLevel := logger.Silent
Expand Down
9 changes: 8 additions & 1 deletion go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,18 @@ require (
gorm.io/gorm v1.25.7
)

require github.com/go-sql-driver/mysql v1.7.1 // indirect
require (
github.com/go-sql-driver/mysql v1.7.1 // indirect
github.com/tidwall/gjson v1.17.0 // indirect
github.com/tidwall/match v1.1.1 // indirect
github.com/tidwall/pretty v1.2.0 // indirect
github.com/tidwall/sjson v1.2.5 // indirect
)

require (
github.com/jinzhu/inflection v1.0.0 // indirect
github.com/jinzhu/now v1.1.5 // indirect
github.com/wI2L/jsondiff v0.5.0
go.uber.org/multierr v1.11.0 // indirect
gorm.io/driver/mysql v1.5.4
)
11 changes: 11 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,17 @@ github.com/jinzhu/inflection v1.0.0 h1:K317FqzuhWc8YvSVlFMCCUb36O/S9MCKRDI7QkRKD
github.com/jinzhu/inflection v1.0.0/go.mod h1:h+uFLlag+Qp1Va5pdKtLDYj+kHp5pxUVkryuEj+Srlc=
github.com/jinzhu/now v1.1.5 h1:/o9tlHleP7gOFmsnYNz3RGnqzefHA47wQpKrrdTIwXQ=
github.com/jinzhu/now v1.1.5/go.mod h1:d3SSVoowX0Lcu0IBviAWJpolVfI5UJVZZ7cO71lE/z8=
github.com/tidwall/gjson v1.14.2/go.mod h1:/wbyibRr2FHMks5tjHJ5F8dMZh3AcwJEMf5vlfC0lxk=
github.com/tidwall/gjson v1.17.0 h1:/Jocvlh98kcTfpN2+JzGQWQcqrPQwDrVEMApx/M5ZwM=
github.com/tidwall/gjson v1.17.0/go.mod h1:/wbyibRr2FHMks5tjHJ5F8dMZh3AcwJEMf5vlfC0lxk=
github.com/tidwall/match v1.1.1 h1:+Ho715JplO36QYgwN9PGYNhgZvoUSc9X2c80KVTi+GA=
github.com/tidwall/match v1.1.1/go.mod h1:eRSPERbgtNPcGhD8UCthc6PmLEQXEWd3PRB5JTxsfmM=
github.com/tidwall/pretty v1.2.0 h1:RWIZEg2iJ8/g6fDDYzMpobmaoGh5OLl4AXtGUGPcqCs=
github.com/tidwall/pretty v1.2.0/go.mod h1:ITEVvHYasfjBbM0u2Pg8T2nJnzm8xPwvNhhsoaGGjNU=
github.com/tidwall/sjson v1.2.5 h1:kLy8mja+1c9jlljvWTlSazM7cKDRfJuR/bOJhcY5NcY=
github.com/tidwall/sjson v1.2.5/go.mod h1:Fvgq9kS/6ociJEDnK0Fk1cpYF4FIW6ZF7LAe+6jwd28=
github.com/wI2L/jsondiff v0.5.0 h1:RRMTi/mH+R2aXcPe1VYyvGINJqQfC3R+KSEakuU1Ikw=
github.com/wI2L/jsondiff v0.5.0/go.mod h1:qqG6hnK0Lsrz2BpIVCxWiK9ItsBCpIZQiv0izJjOZ9s=
go.uber.org/multierr v1.10.0 h1:S0h4aNzvfcFsC3dRF1jLoaov7oRaKqRGC/pUEJ2yvPQ=
go.uber.org/multierr v1.10.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y=
go.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0=
Expand Down
7 changes: 7 additions & 0 deletions log/log.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,13 @@ import (
"go.uber.org/zap/zapcore"
)

// GetLogger returns a new logger with the specified log level.
//
// Parameters:
// - logLevel: a string representing the log level ("debug", "error", "warn", "fatal")
//
// Return type(s):
// - *zap.Logger: a pointer to the logger
func GetLogger(logLevel string) *zap.Logger {
level := zap.InfoLevel
if logLevel == "debug" {
Expand Down
97 changes: 97 additions & 0 deletions test/test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
package log

import (
"bytes"
"crypto/tls"
"encoding/json"
"fmt"
"net/http"
"os"
"reflect"
"strings"

"github.com/wI2L/jsondiff"
)

// MakeRequest makes an HTTP request with the specified verb, URL, payload, schema, and value.
//
// Parameters:
// - verb string: the HTTP verb (GET, POST, PUT, etc.)
// - url string: the URL to make the request to
// - payload string: the payload to include in the request
// - schema string: the type of authentication schema to use (basic, bearer, etc.)
// - value string: the value used for authentication (bearer token for bearer schema, username for basic schema)
//
// Return type(s):
// - *http.Response: the HTTP response
// - error: an error, if any, encountered during the request
func MakeRequest(verb string, url string, payload string, schema string, value string) (*http.Response, error) {
customTransport := http.DefaultTransport.(*http.Transport).Clone()
customTransport.TLSClientConfig = &tls.Config{InsecureSkipVerify: true}
client := &http.Client{Transport: customTransport}

bodyReader := bytes.NewReader([]byte(payload))

req, err := http.NewRequest(verb, "http://localhost:8080"+url, bodyReader)
if err != nil {
return nil, err
}

// set credentials depending on schema
if schema == "basic" {
req.SetBasicAuth(value, "1234")
}
if schema == "bearer" {
req.Header.Add("Authorization", "Bearer "+value)
}
req.Header.Add("Content-Type", "application/json")

resp, err := client.Do(req)
if err != nil {
fmt.Printf("Error calling %s: %s", "http://localhost:8080"+url, err.Error())
return nil, err
}

return resp, nil
}

// CompareResponses compares the actual response with the reference file and returns a boolean indicating the result, a string representing any differences, and an error if any.
//
// Parameters:
// - actual string: the JSON string we want to test against the reference file
// - referenceFilename string: the name of the reference file to compare
//
// Return type(s):
// - bool: whether the actual response matches the reference file
// - string: a string representing any differences
// - error: an error, if any, encountered during the comparison
func CompareResponses(actual string, referenceFilename string) (bool, string, error) {
var v1, v2 interface{}

// marshal actual response date
json.Unmarshal([]byte(actual), &v1)

// read 'expected' data from file
pwd, _ := os.Getwd()
rootPath := strings.ReplaceAll(pwd, "internal/api", "")
b, err := os.ReadFile(rootPath + "assets/tests/" + referenceFilename)
if err != nil {
return false, "", err
}
json.Unmarshal(b, &v2)

if reflect.DeepEqual(v1, v2) {
return true, "", nil
} else {
patch, err := jsondiff.CompareJSON([]byte(actual), b)
if err != nil {
return false, "", err
}
diffs, err := json.MarshalIndent(patch, "", " ")
if err != nil {
return false, "", err
}
//fmt.Printf("%s\n", string(diffs))
return false, string(diffs), nil
}
}

0 comments on commit 4d9edde

Please sign in to comment.