NOISSUE - Fix CI script (#1613)

* Fix CI script

Signed-off-by: dusanb94 <dusan.borovcanin@mainflux.com>

* Fix linter errors

Signed-off-by: dusanb94 <dusan.borovcanin@mainflux.com>

* Add timeout to linter

Signed-off-by: dusanb94 <dusan.borovcanin@mainflux.com>
This commit is contained in:
Dušan Borovčanin
2022-06-09 21:57:37 +02:00
committed by GitHub
parent 758ed6fa02
commit 6c59184d3f
61 changed files with 53 additions and 282 deletions
+3 -7
View File
@@ -49,10 +49,9 @@ const (
)
var (
encKey = []byte("1234567891011121")
addChannels = []string{"1"}
metadata = map[string]interface{}{"meta": "data"}
addReq = struct {
encKey = []byte("1234567891011121")
metadata = map[string]interface{}{"meta": "data"}
addReq = struct {
ThingID string `json:"thing_id"`
ExternalID string `json:"external_id"`
ExternalKey string `json:"external_key"`
@@ -84,9 +83,6 @@ var (
}
bsErrorRes = toJSON(apiutil.ErrorRes{Err: bootstrap.ErrBootstrap.Error()})
authnRes = toJSON(apiutil.ErrorRes{Err: errors.ErrAuthentication.Error()})
authzRes = toJSON(apiutil.ErrorRes{Err: errors.ErrAuthorization.Error()})
malformedRes = toJSON(apiutil.ErrorRes{Err: errors.ErrMalformedEntity.Error()})
extKeyRes = toJSON(apiutil.ErrorRes{Err: bootstrap.ErrExternalKey.Error()})
extSecKeyRes = toJSON(apiutil.ErrorRes{Err: bootstrap.ErrExternalKeySecure.Error()})
missingIDRes = toJSON(apiutil.ErrorRes{Err: apiutil.ErrMissingID.Error()})
-4
View File
@@ -10,10 +10,6 @@ import (
const maxLimitSize = 100
type apiReq interface {
validate() error
}
type addReq struct {
token string
ThingID string `json:"thing_id"`
+2 -5
View File
@@ -13,10 +13,7 @@ import (
"github.com/mainflux/mainflux/pkg/errors"
)
const (
emptyState = -1
notFoundIdx = -1
)
const emptyState = -1
var _ bootstrap.ConfigRepository = (*configRepositoryMock)(nil)
@@ -107,7 +104,7 @@ func (crm *configRepositoryMock) RetrieveAll(token string, filter bootstrap.Filt
for _, v := range crm.configs {
id, _ := strconv.ParseUint(v.MFThing, 10, 64)
if (state == emptyState || v.State == state) &&
(name == "" || strings.Index(strings.ToLower(v.Name), name) != notFoundIdx) &&
(name == "" || strings.Contains(strings.ToLower(v.Name), name)) &&
v.Owner == token {
if id >= first && id < last {
configs = append(configs, v)
+1 -3
View File
@@ -83,9 +83,7 @@ func (svc *mainfluxThings) Connect(_ context.Context, owner string, chIDs, thIDs
if svc.channels[chID].Owner != userID.Email {
return errors.ErrAuthentication
}
for _, thID := range thIDs {
svc.connections[chID] = append(svc.connections[chID], thID)
}
svc.connections[chID] = append(svc.connections[chID], thIDs...)
}
return nil
-4
View File
@@ -18,12 +18,8 @@ import (
const (
duplicateErr = "unique_violation"
uuidErr = "invalid input syntax for type uuid"
fkViolation = "foreign_key_violation"
connConstraintErr = "connections_config_id_config_owner_fkey"
configFieldsNum = 8
chanFieldsNum = 3
connFieldsNum = 2
cleanupQuery = `DELETE FROM channels ch WHERE NOT EXISTS (
SELECT channel_id FROM connections c WHERE ch.mainflux_channel = c.channel_id);`
)
+1 -3
View File
@@ -544,9 +544,7 @@ func TestListExisting(t *testing.T) {
require.Nil(t, err, fmt.Sprintf("Saving config expected to succeed: %s.\n", err))
var chs []bootstrap.Channel
for _, ch := range config.MFChannels {
chs = append(chs, ch)
}
chs = append(chs, config.MFChannels...)
cases := []struct {
desc string
-5
View File
@@ -14,11 +14,6 @@ import (
dockertest "github.com/ory/dockertest/v3"
)
const (
wrongID = "0"
wrongValue = "wrong-value"
)
var (
testLog, _ = logger.New(os.Stdout, logger.Info.String())
db *sqlx.DB
+2 -2
View File
@@ -120,8 +120,8 @@ func TestReadConfig(t *testing.T) {
require.Nil(t, err, fmt.Sprintf("Marshalling expected to succeed: %s.\n", err))
assert.Equal(t, tc.enc, b, fmt.Sprintf("%s: expected %s got %s\n", tc.desc, tc.enc, b))
resp, ok := res.(mainflux.Response)
require.True(t, ok, fmt.Sprintf("If not encrypted, reader should return response."))
require.True(t, ok, "If not encrypted, reader should return response.")
assert.False(t, resp.Empty(), fmt.Sprintf("Response should not be empty %s.", err))
assert.Equal(t, http.StatusOK, resp.Code(), fmt.Sprintf("Default config response code should be 200."))
assert.Equal(t, http.StatusOK, resp.Code(), "Default config response code should be 200.")
}
}
+1 -1
View File
@@ -104,7 +104,7 @@ func decodeRemoveThing(event map[string]interface{}) removeEvent {
func decodeUpdateChannel(event map[string]interface{}) updateChannelEvent {
strmeta := read(event, "metadata", "{}")
var metadata map[string]interface{}
if err := json.Unmarshal([]byte(strmeta), metadata); err != nil {
if err := json.Unmarshal([]byte(strmeta), &metadata); err != nil {
metadata = map[string]interface{}{}
}
-5
View File
@@ -14,11 +14,6 @@ import (
dockertest "github.com/ory/dockertest/v3"
)
const (
wrongID = 0
wrongValue = "wrong-value"
)
var redisClient *redis.Client
func TestMain(m *testing.M) {
+2 -4
View File
@@ -107,7 +107,6 @@ type bootstrapService struct {
configs ConfigRepository
sdk mfsdk.SDK
encKey []byte
reader ConfigReader
}
// New returns new Bootstrap service.
@@ -415,7 +414,7 @@ func (bs bootstrapService) connectionChannels(channels, existing []string, token
}
for _, ch := range existing {
if add[ch] == true {
if add[ch] {
delete(add, ch)
}
}
@@ -442,8 +441,7 @@ func (bs bootstrapService) connectionChannels(channels, existing []string, token
// 2) IDs of Channels to be removed
// 3) IDs of common Channels for these two configs
func (bs bootstrapService) updateList(cfg Config, connections []string) (add, remove []string) {
var disconnect map[string]bool
disconnect = make(map[string]bool, len(cfg.MFChannels))
disconnect := make(map[string]bool, len(cfg.MFChannels))
for _, c := range cfg.MFChannels {
disconnect[c.ID] = true
}
-33
View File
@@ -32,39 +32,6 @@ func issueCert(svc certs.Service) endpoint.Endpoint {
}
}
func listCerts(svc certs.Service) endpoint.Endpoint {
return func(ctx context.Context, request interface{}) (interface{}, error) {
req := request.(listReq)
if err := req.validate(); err != nil {
return nil, err
}
page, err := svc.ListCerts(ctx, req.token, req.thingID, req.offset, req.limit)
if err != nil {
return certsPageRes{}, err
}
res := certsPageRes{
pageRes: pageRes{
Total: page.Total,
Offset: page.Offset,
Limit: page.Limit,
},
Certs: []certsRes{},
}
for _, cert := range page.Certs {
view := certsRes{
CertSerial: cert.Serial,
ThingID: cert.ThingID,
ClientCert: cert.ClientCert,
Expiration: cert.Expire,
}
res.Certs = append(res.Certs, view)
}
return res, nil
}
}
func listSerials(svc certs.Service) endpoint.Endpoint {
return func(ctx context.Context, request interface{}) (interface{}, error) {
req := request.(listReq)
-12
View File
@@ -17,18 +17,6 @@ type Config struct {
RawOutput bool `toml:"raw_output"`
}
// save - store config in a file
func save(c Config, file string) error {
b, err := toml.Marshal(c)
if err != nil {
return errors.New(fmt.Sprintf("failed to read config file: %s", err))
}
if err := ioutil.WriteFile(file, b, 0644); err != nil {
return errors.New(fmt.Sprintf("failed to write config TOML: %s", err))
}
return nil
}
// read - retrieve config from a file
func read(file string) (Config, error) {
data, err := ioutil.ReadFile(file)
-6
View File
@@ -93,7 +93,6 @@ type config struct {
serverCert string
serverKey string
jaegerURL string
resetURL string
ketoReadHost string
ketoWriteHost string
ketoWritePort string
@@ -101,11 +100,6 @@ type config struct {
loginDuration time.Duration
}
type tokenConfig struct {
hmacSampleSecret []byte // secret for signing token
tokenDuration string // token in duration in min
}
func main() {
cfg := loadConfig()
ctx, cancel := context.WithCancel(context.Background())
-1
View File
@@ -36,7 +36,6 @@ import (
const (
stopWaitTime = 5 * time.Second
svcName = "cassandra-reader"
sep = ","
defLogLevel = "error"
defPort = "8180"
+4 -24
View File
@@ -82,7 +82,6 @@ const (
envDBSSLCert = "MF_CERTS_DB_SSL_CERT"
envDBSSLKey = "MF_CERTS_DB_SSL_KEY"
envDBSSLRootCert = "MF_CERTS_DB_SSL_ROOT_CERT"
envEncryptKey = "MF_CERTS_ENCRYPT_KEY"
envClientTLS = "MF_CERTS_CLIENT_TLS"
envCACerts = "MF_CERTS_CA_CERTS"
envServerCert = "MF_CERTS_SERVER_CERT"
@@ -104,21 +103,16 @@ const (
)
var (
errFailedCertLoading = errors.New("failed to load certificate")
errFailedCertDecode = errors.New("failed to decode certificate")
errMissingCACertificate = errors.New("missing CA")
errPrivateKeyEmpty = errors.New("private key empty")
errPrivateKeyUnsupportedType = errors.New("private key unsupported type")
errCertsRemove = errors.New("failed to remove certificate")
errCACertificateNotExist = errors.New("CA certificate does not exist")
errCAKeyNotExist = errors.New("CA certificate key does not exist")
errFailedCertLoading = errors.New("failed to load certificate")
errFailedCertDecode = errors.New("failed to decode certificate")
errCACertificateNotExist = errors.New("CA certificate does not exist")
errCAKeyNotExist = errors.New("CA certificate key does not exist")
)
type config struct {
logLevel string
dbConfig postgres.Config
clientTLS bool
encKey []byte
caCerts string
httpPort string
serverCert string
@@ -248,20 +242,6 @@ func loadConfig() config {
}
func connectToRedis(redisURL, redisPass, redisDB string, logger mflog.Logger) *redis.Client {
db, err := strconv.Atoi(redisDB)
if err != nil {
logger.Error(fmt.Sprintf("Failed to connect to redis: %s", err))
os.Exit(1)
}
return redis.NewClient(&redis.Options{
Addr: redisURL,
Password: redisPass,
DB: db,
})
}
func connectToDB(dbConfig postgres.Config, logger logger.Logger) *sqlx.DB {
db, err := postgres.Connect(dbConfig)
if err != nil {
-1
View File
@@ -32,7 +32,6 @@ import (
const (
stopWaitTime = 5 * time.Second
svcName = "influxdb-reader"
defLogLevel = "error"
defPort = "8180"
defDB = "mainflux"
-1
View File
@@ -36,7 +36,6 @@ import (
const (
stopWaitTime = 5 * time.Second
svcName = "mongodb-reader"
defLogLevel = "error"
defPort = "8180"
defDB = "mainflux"
-6
View File
@@ -206,12 +206,6 @@ func subscribeToStoredSubs(sub opcua.Subscriber, cfg opcua.Config, logger logger
}
}
func subscribeToOpcuaServer(gc opcua.Subscriber, cfg opcua.Config, logger logger.Logger) {
if err := gc.Subscribe(context.Background(), cfg); err != nil {
logger.Warn(fmt.Sprintf("OPC-UA Subscription failed: %s", err))
}
}
func subscribeToThingsES(svc opcua.Service, client *r.Client, prefix string, logger logger.Logger) {
eventStore := redis.NewEventStore(svc, client, prefix, logger)
if err := eventStore.Subscribe(context.Background(), "mainflux.things"); err != nil {
-1
View File
@@ -34,7 +34,6 @@ import (
const (
svcName = "postgres-reader"
sep = ","
stopWaitTime = 5 * time.Second
defLogLevel = "error"
-1
View File
@@ -26,7 +26,6 @@ import (
const (
svcName = "postgres-writer"
sep = ","
stopWaitTime = 5 * time.Second
defLogLevel = "error"
+2 -2
View File
@@ -199,13 +199,13 @@ func loadConfig() (provision.Config, error) {
return provision.Config{}, errors.New("Can't auto whitelist if auto config save is off")
}
keyBits, err := strconv.Atoi(mainflux.Env(envCertsKeyBits, defCertsKeyBits))
if err != nil && provisionX509 == true {
if err != nil && provisionX509 {
return provision.Config{}, errFailSettingKeyBits
}
var content map[string]interface{}
if c := mainflux.Env(envBSContent, defBSContent); c != "" {
if err = json.Unmarshal([]byte(c), content); err != nil {
if err = json.Unmarshal([]byte(c), &content); err != nil {
return provision.Config{}, errFailedToReadBootstrapContent
}
}
-2
View File
@@ -66,7 +66,6 @@ const (
defAdminEmail = ""
defAdminPassword = ""
defPassRegex = "^.{8,}$"
defAdminGroup = "mainflux"
defTokenResetEndpoint = "/reset-request" // URL where user lands after click on the reset link from email
@@ -102,7 +101,6 @@ const (
envEmailPassword = "MF_EMAIL_PASSWORD"
envEmailFromAddress = "MF_EMAIL_FROM_ADDRESS"
envEmailFromName = "MF_EMAIL_FROM_NAME"
envEmailLogLevel = "MF_EMAIL_LOG_LEVEL"
envEmailTemplate = "MF_EMAIL_TEMPLATE"
envTokenResetEndpoint = "MF_TOKEN_RESET_ENDPOINT"
-4
View File
@@ -13,17 +13,13 @@ func NewMock() Logger {
}
func (l loggerMock) Debug(msg string) {
return
}
func (l loggerMock) Info(msg string) {
return
}
func (l loggerMock) Warn(msg string) {
return
}
func (l loggerMock) Error(msg string) {
return
}
+1 -5
View File
@@ -11,11 +11,7 @@ import (
"github.com/mainflux/mainflux/pkg/messaging"
)
const (
protocol = "lora"
thingSuffix = "thing"
channelSuffix = "channel"
)
const protocol = "lora"
var (
// ErrMalformedMessage indicates malformed LoRa message.
-1
View File
@@ -55,5 +55,4 @@ func (b broker) handleMsg(c mqtt.Client, msg mqtt.Message) {
}
b.svc.Publish(context.Background(), m)
return
}
-2
View File
@@ -11,8 +11,6 @@ import (
"github.com/mainflux/mainflux/opcua/db"
)
const protocol = "opcua"
// Service specifies an API that must be fullfiled by the domain service
// implementation, and all of its decorators (e.g. logging & metrics).
type Service interface {
-2
View File
@@ -23,8 +23,6 @@ const (
serverParam = "server"
namespaceParam = "namespace"
identifierParam = "identifier"
defOffset = 0
defLimit = 10
defNamespace = "ns=0" // Standard root namespace
defIdentifier = "i=84" // Standard root identifier
)
-1
View File
@@ -26,7 +26,6 @@ var (
errNotFoundConn = errors.New("connection not found")
errFailedConn = errors.New("failed to connect")
errFailedRead = errors.New("failed to read")
errFailedParseInterval = errors.New("failed to parse subscription interval")
errFailedSub = errors.New("failed to subscribe")
errFailedFindEndpoint = errors.New("failed to find suitable endpoint")
+1 -1
View File
@@ -104,7 +104,7 @@ func New(text string) Error {
}
func SignalHandler(ctx context.Context) error {
c := make(chan os.Signal)
c := make(chan os.Signal, 2)
signal.Notify(c, syscall.SIGINT, syscall.SIGABRT)
select {
case sig := <-c:
-1
View File
@@ -11,7 +11,6 @@ import (
)
const (
protocol = "mqtt"
username = "mainflux-mqtt"
qos = 2
)
+1 -1
View File
@@ -62,7 +62,7 @@ func TestMain(m *testing.M) {
}
func handleInterrupt(pool *dockertest.Pool, container *dockertest.Resource) {
c := make(chan os.Signal)
c := make(chan os.Signal, 2)
signal.Notify(c, os.Interrupt, syscall.SIGTERM)
go func() {
<-c
+1 -1
View File
@@ -62,7 +62,7 @@ func TestMain(m *testing.M) {
}
func handleInterrupt(pool *dockertest.Pool, container *dockertest.Resource) {
c := make(chan os.Signal)
c := make(chan os.Signal, 2)
signal.Notify(c, os.Interrupt, syscall.SIGTERM)
go func() {
<-c
+3 -3
View File
@@ -353,7 +353,7 @@ func (ps *provisionService) recover(e *error, ths *[]SDK.Thing, chs *[]SDK.Chann
if errors.Contains(err, ErrFailedBootstrapValidate) || errors.Contains(err, ErrFailedCertCreation) {
clean(ps, things, channels, token)
for _, th := range things {
if needsBootstrap(th) == true {
if needsBootstrap(th) {
ps.errLog(ps.sdk.RemoveBootstrap(token, th.ID))
}
@@ -364,7 +364,7 @@ func (ps *provisionService) recover(e *error, ths *[]SDK.Thing, chs *[]SDK.Chann
if errors.Contains(err, ErrFailedBootstrapValidate) || errors.Contains(err, ErrFailedCertCreation) {
clean(ps, things, channels, token)
for _, th := range things {
if needsBootstrap(th) == true {
if needsBootstrap(th) {
bs, err := ps.sdk.ViewBootstrap(token, th.ID)
ps.errLog(errors.Wrap(ErrFailedBootstrapRetrieval, err))
ps.errLog(ps.sdk.RemoveBootstrap(token, bs.MFThing))
@@ -378,7 +378,7 @@ func (ps *provisionService) recover(e *error, ths *[]SDK.Thing, chs *[]SDK.Chann
if ps.conf.Bootstrap.X509Provision && needsBootstrap(th) {
ps.errLog(ps.sdk.RemoveCert(th.ID, token))
}
if needsBootstrap(th) == true {
if needsBootstrap(th) {
bs, err := ps.sdk.ViewBootstrap(token, th.ID)
ps.errLog(errors.Wrap(ErrFailedBootstrapRetrieval, err))
ps.errLog(ps.sdk.RemoveBootstrap(token, bs.MFThing))
-2
View File
@@ -6,7 +6,6 @@ package api_test
import (
"encoding/json"
"fmt"
"io"
"net/http"
"net/http/httptest"
"testing"
@@ -61,7 +60,6 @@ type testRequest struct {
url string
token string
key string
body io.Reader
}
func (tr testRequest) make() (*http.Response, error) {
-4
View File
@@ -10,10 +10,6 @@ import (
const maxLimitSize = 1000
type apiReq interface {
validate() error
}
type listMessagesReq struct {
chanID string
token string
-1
View File
@@ -14,7 +14,6 @@ import (
)
const (
format = "format"
// Table for SenML messages
defTable = "messages"
+2 -5
View File
@@ -15,11 +15,8 @@ import (
"go.mongodb.org/mongo-driver/mongo/options"
)
const (
format = "format"
// Collection for SenML messages
defCollection = "messages"
)
// Collection for SenML messages
const defCollection = "messages"
var _ readers.MessageRepository = (*mongoRepository)(nil)
-1
View File
@@ -24,7 +24,6 @@ import (
const (
testDB = "test"
collection = "messages"
subtopic = "subtopic"
msgsNum = 100
limit = 10
-3
View File
@@ -14,10 +14,7 @@ import (
"github.com/mainflux/mainflux/readers"
)
const errInvalid = "invalid_text_representation"
const (
format = "format"
// Table for SenML messages
defTable = "messages"
-1
View File
@@ -29,7 +29,6 @@ const (
format1 = "format1"
format2 = "format2"
wrongID = "0"
wrongValue = "wrong-value"
)
var (
+1 -5
View File
@@ -12,15 +12,11 @@ import (
"testing"
"github.com/jmoiron/sqlx"
"github.com/mainflux/mainflux/logger"
"github.com/mainflux/mainflux/readers/postgres"
dockertest "github.com/ory/dockertest/v3"
)
var (
testLog, _ = logger.New(os.Stdout, logger.Info.String())
db *sqlx.DB
)
var db *sqlx.DB
func TestMain(m *testing.M) {
pool, err := dockertest.NewPool("")
-3
View File
@@ -15,14 +15,11 @@ import (
)
const (
format = "format"
// Table for SenML messages
defTable = "messages"
// Error code for Undefined table error.
undefinedTableCode = "42P01"
errInvalid = "invalid_text_representation"
)
var _ readers.MessageRepository = (*timescaleRepository)(nil)
-1
View File
@@ -29,7 +29,6 @@ const (
format1 = "format1"
format2 = "format2"
wrongID = "0"
wrongValue = "wrong-value"
)
var (
+1 -5
View File
@@ -12,15 +12,11 @@ import (
"testing"
"github.com/jmoiron/sqlx"
"github.com/mainflux/mainflux/logger"
"github.com/mainflux/mainflux/readers/timescale"
dockertest "github.com/ory/dockertest/v3"
)
var (
testLog, _ = logger.New(os.Stdout, logger.Info.String())
db *sqlx.DB
)
var db *sqlx.DB
func TestMain(m *testing.M) {
pool, err := dockertest.NewPool("")
+16 -23
View File
@@ -1,10 +1,9 @@
# This script contains commands to be executed by the CI tool.
NPROC=$(nproc)
GO_VERSION=1.17
GO_VERSION=1.18.3
PROTOC_VERSION=3.12.3
PROTOC_GEN_VERSION=v1.4.2
PROTOC_GOFAST_VERSION=v1.3.1
GRPC_VERSION=v1.29.1
function version_gt() { test "$(printf '%s\n' "$@" | sort -V | head -n 1)" != "$1"; }
@@ -12,28 +11,24 @@ update_go() {
CURRENT_GO_VERSION=$(go version | sed 's/[^0-9.]*\([0-9.]*\).*/\1/')
if version_gt $GO_VERSION $CURRENT_GO_VERSION; then
echo "Updating go version from $CURRENT_GO_VERSION to $GO_VERSION ..."
sudo rm -rf /usr/local/go
sudo rm -rf /usr/local/golang
sudo rm -rf /usr/bin/go
wget https://dl.google.com/go/go$GO_VERSION.linux-amd64.tar.gz
tar -xvf go$GO_VERSION.linux-amd64.tar.gz
rm go$GO_VERSION.linux-amd64.tar.gz
sudo mv go /usr/local
export GOROOT=/usr/local/go
export GOPATH=/home/runner/go/src
export GOBIN=/home/runner/go/bin
mkdir -p $GOPATH
mkdir $GOBIN
# remove other Go version from path
export PATH=$PATH:/usr/local/go/bin:$GOBIN
sudo rm -rf /usr/bin/go
sudo rm -rf /usr/local/go
sudo rm -rf /usr/local/bin/go
sudo rm -rf /usr/local/golang
sudo rm -rf $GOROOT $GOPAT $GOBIN
wget https://go.dev/dl/go$GO_VERSION.linux-amd64.tar.gz
sudo tar -C /usr/local -xzf go$GO_VERSION.linux-amd64.tar.gz
export GOROOT=/usr/local/go
export PATH=$PATH:/usr/local/go/bin
fi
export GOBIN=$HOME/go/bin
export PATH=$PATH:$GOBIN
go version
}
setup_protoc() {
# Execute `go get` for protoc dependencies outside of project dir.
cd ..
export GO111MODULE=on
echo "Setting up protoc..."
PROTOC_ZIP=protoc-$PROTOC_VERSION-linux-x86_64.zip
curl -0L https://github.com/google/protobuf/releases/download/v$PROTOC_VERSION/$PROTOC_ZIP -o $PROTOC_ZIP
@@ -42,12 +37,10 @@ setup_protoc() {
sudo mv protoc3/include/* /usr/local/include/
rm -f PROTOC_ZIP
go get -u github.com/golang/protobuf/protoc-gen-go@$PROTOC_GEN_VERSION \
github.com/gogo/protobuf/protoc-gen-gofast@$PROTOC_GOFAST_VERSION \
google.golang.org/grpc@$GRPC_VERSION
go install github.com/golang/protobuf/protoc-gen-go@$PROTOC_GEN_VERSION
go install github.com/gogo/protobuf/protoc-gen-gofast@$PROTOC_GOFAST_VERSION
export PATH=$PATH:/usr/local/bin/protoc
cd mainflux
}
setup_mf() {
@@ -76,7 +69,7 @@ setup_mf() {
setup_lint() {
# binary will be $(go env GOBIN)/golangci-lint
curl -sSfL https://raw.githubusercontent.com/golangci/golangci-lint/master/install.sh | sh -s -- -b $(go env GOBIN) v1.24.0
curl -sSfL https://raw.githubusercontent.com/golangci/golangci-lint/master/install.sh | sh -s -- -b $(go env GOBIN) v1.46.2
}
@@ -90,7 +83,7 @@ setup() {
run_test() {
echo "Running lint..."
golangci-lint run --no-config --disable-all --enable=golint
golangci-lint run --no-config --disable-all --enable gosimple --enable govet --enable unused --enable deadcode --timeout 3m
echo "Running tests..."
echo "" > coverage.txt
for d in $(go list ./... | grep -v 'vendor\|cmd'); do
+1 -1
View File
@@ -88,7 +88,7 @@ func Benchmark(cfg Config) {
<-finishedPub
totalTime := time.Now().Sub(start)
totalTime := time.Since(start)
totals := calculateTotalResults(results, totalTime, subsResults)
if totals == nil {
return
+2 -3
View File
@@ -67,7 +67,7 @@ func calcMsgRes(m *message, res *runResults) *float64 {
}
func calcRes(r *runResults, start time.Time, times []float64) *runResults {
duration := time.Now().Sub(start)
duration := time.Since(start)
timeMatrix := mat.NewDense(1, len(times), times)
r.MsgTimeMin = mat.Min(timeMatrix)
r.MsgTimeMax = mat.Max(timeMatrix)
@@ -159,7 +159,7 @@ func printResults(results []*runResults, totals *totalResults, format string, qu
var out bytes.Buffer
json.Indent(&out, data, "", "\t")
fmt.Println(string(out.Bytes()))
fmt.Println(out.String())
default:
if !quiet {
for _, res := range results {
@@ -190,5 +190,4 @@ func printResults(results []*runResults, totals *totalResults, format string, qu
fmt.Printf("Average Bandwidth (msg/sec): %.3f\n", totals.AvgMsgsPerSec)
fmt.Printf("Total Bandwidth (msg/sec): %.3f\n", totals.TotalMsgsPerSec)
}
return
}
-5
View File
@@ -10,11 +10,6 @@ import (
"github.com/spf13/cobra"
)
// Keep struct names exported, otherwise Viper unmarshaling won't work
type mqttBrokerCfg struct {
URL string `toml:"url" mapstructure:"url"`
}
func main() {
pconf := provision.Config{}
+1 -5
View File
@@ -18,11 +18,7 @@ import (
"github.com/mainflux/mainflux/twins/mocks"
)
const (
nanosec = 1e9
publisher = "twins"
numRecs = 100
)
const numRecs = 100
var (
subtopics = []string{"engine", "chassis", "wheel_2"}
-2
View File
@@ -32,13 +32,11 @@ const (
wrongValue = "wrong_value"
wrongID = 0
maxNameSize = 1024
topic = "topic"
)
var invalidName = strings.Repeat("m", maxNameSize+1)
type twinReq struct {
token string
Name string `json:"name,omitempty"`
Metadata map[string]interface{} `json:"metadata,omitempty"`
}
-4
View File
@@ -13,10 +13,6 @@ const (
maxLimitSize = 100
)
type apiReq interface {
validate() error
}
type addTwinReq struct {
token string
Name string `json:"name,omitempty"`
+1 -4
View File
@@ -15,10 +15,7 @@ import (
dockertest "github.com/ory/dockertest/v3"
)
const (
wrongID = "0"
wrongValue = "wrong-value"
)
const wrongValue = "wrong-value"
func TestMain(m *testing.M) {
pool, err := dockertest.NewPool("")
+1 -2
View File
@@ -19,8 +19,7 @@ const (
)
type twinRepository struct {
db *mongo.Database
subtopicWildcard string
db *mongo.Database
}
var _ twins.TwinRepository = (*twinRepository)(nil)
-2
View File
@@ -25,7 +25,6 @@ import (
const (
maxNameSize = 1024
msgsNum = 10
testDB = "test"
collection = "twins"
email = "mfx_twin@example.com"
@@ -38,7 +37,6 @@ var (
addr string
testLog, _ = log.New(os.Stdout, log.Info.String())
idProvider = uuid.New()
db mongo.Database
invalidName = strings.Repeat("m", maxNameSize+1)
)
-5
View File
@@ -14,11 +14,6 @@ import (
dockertest "github.com/ory/dockertest/v3"
)
const (
wrongID = 0
wrongValue = "wrong-value"
)
var redisClient *redis.Client
func TestMain(m *testing.M) {
-1
View File
@@ -22,7 +22,6 @@ const (
token = "token"
wrongToken = "wrong-token"
email = "user@example.com"
natsURL = "nats://localhost:4222"
numRecs = 100
)
-1
View File
@@ -15,7 +15,6 @@ const (
updateStateOp = "update_state"
countStatesOp = "count_states"
retrieveAllStatesOp = "retrieve_all_states"
retrieveLastStateOp = "retrieve_states_by_attribute"
)
var _ twins.StateRepository = (*stateRepositoryMiddleware)(nil)
-1
View File
@@ -50,7 +50,6 @@ var (
missingEmailRes = toJSON(apiutil.ErrorRes{Err: apiutil.ErrMissingEmail.Error()})
missingPassRes = toJSON(apiutil.ErrorRes{Err: apiutil.ErrMissingPass.Error()})
invalidRestPassRes = toJSON(apiutil.ErrorRes{Err: apiutil.ErrInvalidResetPass.Error()})
failDecodeRes = toJSON(apiutil.ErrorRes{Err: errors.ErrMalformedEntity.Error()})
passRegex = regexp.MustCompile("^.{8,}$")
)
-35
View File
@@ -6,7 +6,6 @@ package postgres
import (
"context"
"database/sql"
"database/sql/driver"
"encoding/json"
"fmt"
"strings"
@@ -228,40 +227,6 @@ func (ur userRepository) UpdatePassword(ctx context.Context, email, password str
return nil
}
// dbMetadata type for handling metadata properly in database/sql
type dbMetadata map[string]interface{}
// Scan - Implement the database/sql scanner interface
func (m *dbMetadata) Scan(value interface{}) error {
if value == nil {
return nil
}
b, ok := value.([]byte)
if !ok {
return errors.ErrScanMetadata
}
if err := json.Unmarshal(b, m); err != nil {
return err
}
return nil
}
// Value Implements valuer
func (m dbMetadata) Value() (driver.Value, error) {
if len(m) == 0 {
return nil, nil
}
b, err := json.Marshal(m)
if err != nil {
return nil, err
}
return b, err
}
type dbUser struct {
ID string `db:"id"`
Email string `db:"email"`
+2 -2
View File
@@ -24,11 +24,11 @@ const (
var (
userRegexp = regexp.MustCompile("^[a-zA-Z0-9!#$%&'*+/=?^_`{|}~.-]+$")
hostRegexp = regexp.MustCompile("^[^\\s]+\\.[^\\s]+$")
hostRegexp = regexp.MustCompile(`^[^\s]+\.[^\s]+$`)
userDotRegexp = regexp.MustCompile("(^[.]{1})|([.]{1}$)|([.]{2,})")
)
// Metadata to be used for mainflux thing or channel for customized
// Metadata to be used for Mainflux thing or channel for customized
// describing of particular thing or channel.
type Metadata map[string]interface{}