Skip to content

Commit

Permalink
Merge pull request #27 from mmatur/fix/ci
Browse files Browse the repository at this point in the history
Refacto for tests
  • Loading branch information
lbroudoux authored Nov 14, 2024
2 parents e43a4b4 + f0c5c04 commit da4a476
Show file tree
Hide file tree
Showing 22 changed files with 950 additions and 800 deletions.
13 changes: 11 additions & 2 deletions .github/workflows/build-test.yml
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,10 @@ on:
- 'LICENSE'
- '*.md'
permissions: read-all

env:
GOLANGCI_LINT_VERSION: v1.62.0

jobs:
build:
runs-on: ubuntu-latest
Expand All @@ -29,8 +33,13 @@ jobs:
go-version-file: ./go.mod
cache-dependency-path: ./go.sum

- name: golangci-lint
uses: golangci/golangci-lint-action@v6
with:
version: "${{ env.GOLANGCI_LINT_VERSION }}"

- name: Build
run: go build -v ./...
run: make build

- name: Test
run: go test -v ./...
run: make test
118 changes: 118 additions & 0 deletions .golangci.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,118 @@
run:
timeout: 10m
linters:
enable-all: true
disable:
- sqlclosecheck # not relevant (SQL)
- rowserrcheck # not relevant (SQL)
- cyclop # duplicate of gocyclo
- lll # Not relevant
- gocognit # Too strict
- nestif # Too many false-positive.
- prealloc # Too many false-positive.
- makezero # Not relevant
- dupl # Too strict
- gosec # Too strict
- gochecknoinits
- gochecknoglobals
- wsl # Too strict
- nlreturn # Not relevant
- nlreturn # Not relevant
- gomnd # Too strict
- mnd # Too strict
- errorlint # Too strict
- errchkjson # Too strict
- stylecheck # skip because report issues related to some generated files.
- testpackage # Too strict
- tparallel # Not relevant
- paralleltest # Not relevant
- exhaustive # Not relevant
- exhaustruct # Not relevant
- err113 # Too strict
- wrapcheck # Too strict
- noctx # Too strict
- bodyclose # too many false-positive
- forcetypeassert # Too strict
- tagliatelle # Too strict
- varnamelen # Not relevant
- nilnil # Not relevant
- ireturn # Not relevant
- contextcheck # too many false-positive
- containedctx # too many false-positive
- maintidx # kind of duplicate of gocyclo
- nonamedreturns # Too strict
- gosmopolitan # not relevant
- exportloopref # Not relevant since go1.22
- depguard # Not relevant
linters-settings:
revive:
rules:
- name: struct-tag
- name: blank-imports
- name: context-as-argument
- name: context-keys-type
- name: dot-imports
- name: error-return
- name: error-strings
- name: error-naming
- name: exported
disabled: true
- name: if-return
- name: increment-decrement
- name: var-naming
- name: var-declaration
- name: package-comments
disabled: true
- name: range
- name: receiver-naming
- name: time-naming
- name: unexported-return
- name: indent-error-flow
- name: errorf
- name: empty-block
- name: superfluous-else
- name: unused-parameter
disabled: true
- name: unreachable-code
- name: redefines-builtin-id
funlen:
lines: -1
statements: 120
forbidigo:
forbid:
- ^print(ln)?$
- ^spew\.Print(f|ln)?$
- ^spew\.Dump$
goheader:
template: |-
Copyright The Microcks Authors.
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.
issues:
exclude-use-default: false
max-issues-per-linter: 0
max-same-issues: 0
exclude:
- 'Error return value of .((os\.)?std(out|err)\..*|.*Close|.*Flush|os\.Remove(All)?|.*printf?|os\.(Un)?Setenv). is not checked'
- "should have a package comment, unless it's in another file for this package"
- 'fmt.Sprintf can be replaced with string'
exclude-rules:
- path: '(.+)_test.go'
linters:
- goconst
- funlen
- godot
- canonicalheader
- fatcontext
10 changes: 10 additions & 0 deletions Makefile
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
.PHONY: lint build test

lint:
golangci-lint run

build:
go build -v ./...

test:
go test -v ./...
8 changes: 4 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -133,11 +133,11 @@ ok github.com/microcks/microcks-testcontainers-go-demo/internal/client
```

```sh
$ go test -timeout 30s -run "^TestOpenAPIContractAdvanced$" ./internal/controller -v
$ go test ./internal/test -test.timeout=20m -failfast -v -test.run TestBaseSuite -testify.m ^TestOpenAPIContractAdvanced

$ go test -timeout 30s -run "^TestPostmanCollectionContract$" ./internal/controller -v
$ go test ./internal/test -test.timeout=20m -failfast -v -test.run TestBaseSuite -testify.m ^TestPostmanCollectionContract

$ go test -timeout 30s -run "^TestOrderEventIsPublishedWhenOrderIsCreated$" ./internal/service -v
$ go test ./internal/test -test.timeout=20m -failfast -v -test.run TestBaseSuite -testify.m ^TestOrderEventIsPublishedWhenOrderIsCreated

$ go test -timeout 30s -run "^TestEventIsConsumedAndProcessedByService$" ./internal/service -v
$ go test ./internal/test -test.timeout=20m -failfast -v -test.run TestBaseSuite -testify.m ^TestEventIsConsumedAndProcessedByService
```
162 changes: 117 additions & 45 deletions cmd/main.go
Original file line number Diff line number Diff line change
@@ -1,72 +1,144 @@
/*
* Copyright The Microcks Authors.
*
* 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.
*/
// Copyright The Microcks Authors.
//
// 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 main

import (
"context"
"fmt"
"log"
"os"
"os/signal"
"syscall"
"time"

"github.com/confluentinc/confluent-kafka-go/v2/kafka"
run "github.com/microcks/microcks-testcontainers-go-demo/cmd/run"
internal "github.com/microcks/microcks-testcontainers-go-demo/internal"
server "github.com/microcks/microcks-testcontainers-go-demo/cmd/run"
"github.com/microcks/microcks-testcontainers-go-demo/internal"
)

var close chan bool
const (
defaultPastryAPIURL = "http://localhost:9090/rest/API+Pastries/0.0.1"
defaultKafkaBootstrap = "localhost:9092"
shutdownTimeout = 15 * time.Second
defaultOrdersTopic = "orders-created"
defaultReviewedTopic = "OrderEventsAPI-0.1.0-orders-reviewed"
)

func main() {
pastryAPIBaseURL, present := os.LookupEnv("PASTRY_API_URL")
if !present {
pastryAPIBaseURL = "http://localhost:9090/rest/API+Pastries/0.0.1"
// Config holds all application configuration.
type Config struct {
PastryAPIURL string
KafkaBootstrap string
OrdersTopic string
ReviewedTopic string
}

// loadConfig loads configuration from environment variables with defaults.
func loadConfig() *Config {
return &Config{
PastryAPIURL: getEnv("PASTRY_API_URL", defaultPastryAPIURL),
KafkaBootstrap: getEnv("KAFKA_BOOTSTRAP_URL", defaultKafkaBootstrap),
OrdersTopic: getEnv("ORDERS_TOPIC", defaultOrdersTopic),
ReviewedTopic: getEnv("REVIEWED_TOPIC", defaultReviewedTopic),
}
}

// getEnv retrieves an environment variable with a default value.
func getEnv(key, defaultValue string) string {
if value, exists := os.LookupEnv(key); exists {
return value
}
kafkaBootstrapURL, present := os.LookupEnv("KAFKA_BOOTSTRAP_URL")
if !present {
kafkaBootstrapURL = "localhost:9092"
return defaultValue
}

func main() {
if err := run(); err != nil {
log.Fatalf("Application error: %v", err)
}
}

applicationProperties := &internal.ApplicationProperties{
PastriesBaseUrl: pastryAPIBaseURL,
OrderEventsCreatedTopic: "orders-created",
//OrderEventsReviewedTopic: "orders-reviewed",
OrderEventsReviewedTopic: "OrderEventsAPI-0.1.0-orders-reviewed",
func run() error {
// Setup logging
log.SetFlags(log.Ldate | log.Ltime | log.Lmicroseconds | log.Lshortfile)

// Load configuration
config := loadConfig()

// Create application properties
appProps := &internal.ApplicationProperties{
PastriesBaseURL: config.PastryAPIURL,
OrderEventsCreatedTopic: config.OrdersTopic,
OrderEventsReviewedTopic: config.ReviewedTopic,
KafkaConfigMap: &kafka.ConfigMap{
"bootstrap.servers": kafkaBootstrapURL,
"bootstrap.servers": config.KafkaBootstrap,
"group.id": "order-service",
"auto.offset.reset": "latest",
},
}

appServicesChan := make(chan internal.ApplicationServices)
app := run.NewApplication()
go app.Start(*applicationProperties, appServicesChan)
_ = <-appServicesChan
// Create application
app := server.NewApplication(appProps)

// Setup error channel
errChan := make(chan error, 1)

// Start application in a goroutine
go func() {
log.Printf("Starting application with Pastry API URL: %s, Kafka bootstrap: %s",
config.PastryAPIURL, config.KafkaBootstrap)
if err := app.Start(); err != nil {
errChan <- fmt.Errorf("failed to start application: %w", err)
}
}()

// Setup signal handling
sigChan := make(chan os.Signal, 1)
signal.Notify(sigChan, syscall.SIGINT, syscall.SIGTERM)

// Wait for shutdown signal or error
var shutdownErr error
select {
case sig := <-sigChan:
log.Printf("Received signal: %v", sig)
case err := <-errChan:
log.Printf("Received error: %v", err)
shutdownErr = err
}

// Graceful shutdown
log.Println("Starting graceful shutdown...")

// Setup signal hooks.
sigs := make(chan os.Signal, 1)
signal.Notify(sigs, syscall.SIGINT, syscall.SIGTERM)
close = make(chan bool, 1)
// Create shutdown context with timeout
shutdownCtx, shutdownCancel := context.WithTimeout(context.Background(), shutdownTimeout)
defer shutdownCancel()

// Stop the application
shutdownChan := make(chan struct{})
go func() {
sig := <-sigs
fmt.Println("Caught signal " + sig.String())
close <- true
if err := app.Stop(); err != nil {
log.Printf("Error during shutdown: %v", err)
}
close(shutdownChan)
}()

<-close
app.Stop()
fmt.Println("Exiting Microcks TestContainers Go Demo application main.")
// Wait for shutdown or timeout
select {
case <-shutdownCtx.Done():
return fmt.Errorf("shutdown timed out: %v", shutdownCtx.Err())
case <-shutdownChan:
log.Println("Graceful shutdown completed")
}

return shutdownErr
}
Loading

0 comments on commit da4a476

Please sign in to comment.