Repository: trustwallet/blockatlas
Pull request #1021 (2020-04-08 20:28:20)

Add codecov


Patch:
diff --git a/.codecov.yml b/.codecov.yml
new file mode 100644
index 0000000..aab63c6
--- /dev/null
+++ b/.codecov.yml
@@ -0,0 +1,12 @@
+coverage:
+  range: 70..100
+  round: down
+  precision: 0
+
+  status:
+    project:
+      default:
+        # basic
+        target: 30%
+
+
diff --git a/.gitignore b/.gitignore
index 4dd133c..5cf4f5a 100644
--- a/.gitignore
+++ b/.gitignore
@@ -19,6 +19,7 @@ cmd/__debug_bin
 config_*.yml
 *.orig
 *~
+coverage.txt
 
 ### macOS ###
 *.DS_Store
diff --git a/Makefile b/Makefile
index 18f743f..8891548 100644
--- a/Makefile
+++ b/Makefile
@@ -243,7 +243,7 @@ go-clean:
 
 go-test:
 	@echo "  >  Running unit tests"
-	GOBIN=$(GOBIN) go test -cover -race -v ./...
+	GOBIN=$(GOBIN) go test -cover -race -coverprofile=coverage.txt -covermode=atomic -v ./...
 
 go-integration:
 	@echo "  >  Running integration tests"
diff --git a/README.md b/README.md
index 5c674aa..2940eb4 100644
--- a/README.md
+++ b/README.md
@@ -2,7 +2,7 @@
 
 ![Go Version](https://img.shields.io/github/go-mod/go-version/TrustWallet/blockatlas)
 [![Build Status](https://dev.azure.com/TrustWallet/Trust%20BlockAtlas/_apis/build/status/TrustWallet.blockatlas?branchName=master)](https://dev.azure.com/TrustWallet/Trust%20BlockAtlas/_build/latest?definitionId=27&branchName=master)
-[![Codacy Badge](https://api.codacy.com/project/badge/Grade/43834b0c94ad4f6088629aa3e3bb5e94)](https://www.codacy.com/app/TrustWallet/blockatlas?utm_source=github.com&amp;utm_medium=referral&amp;utm_content=TrustWallet/blockatlas&amp;utm_campaign=Badge_Grade)
+[![Codacy Badge](https://api.codacy.com/project/badge/Grade/f11889e08c604dd08c28b76c350a6c4f)](https://www.codacy.com/gh/trustwallet/blockatlas?utm_source=github.com&amp;utm_medium=referral&amp;utm_content=trustwallet/blockatlas&amp;utm_campaign=Badge_Grade)
 [![Go Report Card](https://goreportcard.com/badge/trustwallet/blockatlas)](https://goreportcard.com/report/TrustWallet/blockatlas)
 
 > BlockAtlas is a clean explorer API and transaction observer for cryptocurrencies.
diff --git a/api/endpoint/transaction.go b/api/endpoint/transaction.go
index 6769021..52ba419 100644
--- a/api/endpoint/transaction.go
+++ b/api/endpoint/transaction.go
@@ -78,11 +78,6 @@ func GetTransactionsHistory(c *gin.Context, txAPI blockatlas.TxAPI, tokenTxAPI b
 
 	page := make(blockatlas.TxPage, 0)
 	for _, tx := range txs {
-		if tx.Direction != "" {
-			page = append(page, tx)
-			continue
-		}
-
 		tx.Direction = tx.GetTransactionDirection(address)
 		page = append(page, tx)
 	}
diff --git a/api/middleware/cache.go b/api/middleware/cache.go
index 8d87aa0..916483a 100644
--- a/api/middleware/cache.go
+++ b/api/middleware/cache.go
@@ -120,21 +120,21 @@ func (mc *memCache) setCache(k string, x interface{}, d time.Duration) {
 	memoryCache.cache.Set(k, b, d)
 }
 
-func (mc *memCache) getCache(key string) (cacheResponse, time.Time, error) {
+func (mc *memCache) getCache(key string) (cacheResponse, error) {
 	var result cacheResponse
-	c, exp, ok := mc.cache.GetWithExpiration(key)
+	c, ok := mc.cache.Get(key)
 	if !ok {
-		return result, time.Time{}, fmt.Errorf("gin-cache: invalid cache key %s", key)
+		return result, fmt.Errorf("gin-cache: invalid cache key %s", key)
 	}
 	r, ok := c.([]byte)
 	if !ok {
-		return result, time.Time{}, errors.E("validator cache: failed to cast cache to bytes")
+		return result, errors.E("validator cache: failed to cast cache to bytes")
 	}
 	err := json.Unmarshal(r, &result)
 	if err != nil {
-		return result, time.Time{}, errors.E(err, "not found")
+		return result, errors.E(err, "not found")
 	}
-	return result, exp, nil
+	return result, nil
 }
 
 func generateKey(c *gin.Context) string {
@@ -154,12 +154,12 @@ func CacheMiddleware(expiration time.Duration, handle gin.HandlerFunc) gin.Handl
 	return func(c *gin.Context) {
 		defer c.Next()
 		key := generateKey(c)
-		mc, exp, err := memoryCache.getCache(key)
+		cacheControlValue := uint(expiration.Seconds())
+		mc, err := memoryCache.getCache(key)
 		if err != nil || mc.Data == nil {
 			writer := newCachedWriter(expiration, c.Writer, key)
 
-			expForSet := uint(expiration.Seconds())
-			writer.Header().Set("Cache-Control", fmt.Sprintf("max-age=%d", expForSet))
+			writer.Header().Set("Cache-Control", fmt.Sprintf("max-age=%d", cacheControlValue))
 
 			c.Writer = writer
 			handle(c)
@@ -176,13 +176,7 @@ func CacheMiddleware(expiration time.Duration, handle gin.HandlerFunc) gin.Handl
 			}
 		}
 
-		expCacheTime := (exp.UnixNano() - time.Now().UnixNano()) / int64(time.Second)
-
-		if expCacheTime < 0 {
-			logger.Error("Invalid expiration time")
-		} else {
-			c.Writer.Header().Set("Cache-Control", fmt.Sprintf("max-age=%d", expCacheTime))
-		}
+		c.Writer.Header().Set("Cache-Control", fmt.Sprintf("max-age=%d", cacheControlValue))
 
 		_, err = c.Writer.Write(mc.Data)
 		if err != nil {
diff --git a/api/registry.go b/api/registry.go
index aabe416..8d1518e 100644
--- a/api/registry.go
+++ b/api/registry.go
@@ -3,9 +3,11 @@ package api
 import (
 	"github.com/gin-gonic/gin"
 	"github.com/trustwallet/blockatlas/api/endpoint"
+	"github.com/trustwallet/blockatlas/api/middleware"
 	"github.com/trustwallet/blockatlas/coin"
 	"github.com/trustwallet/blockatlas/pkg/blockatlas"
 	"github.com/trustwallet/blockatlas/platform"
+	"time"
 )
 
 func RegisterCollectionsAPI(root gin.IRouter, api blockatlas.Platform) {
@@ -65,9 +67,9 @@ func RegisterStakeAPI(root gin.IRouter, api blockatlas.Platform) {
 	}
 	handle := api.Coin().Handle
 
-	root.GET("/v2/"+handle+"/staking/validators", func(c *gin.Context) {
+	root.GET("/v2/"+handle+"/staking/validators", middleware.CacheMiddleware(time.Hour, func(c *gin.Context) {
 		endpoint.GetValidators(c, stakingAPI)
-	})
+	}))
 	root.GET("/v2/"+handle+"/staking/delegations/:address", func(c *gin.Context) {
 		endpoint.GetStakingDelegationsForSpecificCoin(c, stakingAPI)
 	})
@@ -77,9 +79,9 @@ func RegisterBatchAPI(root gin.IRouter) {
 	root.POST("v2/staking/delegations", func(c *gin.Context) {
 		endpoint.GetStakeDelegationsWithAllInfoForBatch(c, platform.StakeAPIs)
 	})
-	root.POST("v2/staking/list", func(c *gin.Context) {
+	root.POST("v2/staking/list", middleware.CacheMiddleware(time.Hour, func(c *gin.Context) {
 		endpoint.GetStakeInfoForBatch(c, platform.StakeAPIs)
-	})
+	}))
 	root.POST("/v3/collectibles/categories", func(c *gin.Context) {
 		endpoint.GetCollectionCategoriesFromListV3(c, platform.CollectionAPIs)
 	})
diff --git a/azure-pipelines.yml b/azure-pipelines.yml
index f359b90..fcde072 100644
--- a/azure-pipelines.yml
+++ b/azure-pipelines.yml
@@ -49,6 +49,9 @@ jobs:
       - script: make test
         workingDirectory: '$(System.DefaultWorkingDirectory)'
         displayName: 'Run unit tests'
+      - script: bash <(curl -s https://codecov.io/bash) -f coverage.txt
+        workingDirectory: '$(System.DefaultWorkingDirectory)'
+        displayName: 'Upload coverage to codecov.io'
 
   - job: mocked_tests
     dependsOn: environment
diff --git a/pkg/blockatlas/tx.go b/pkg/blockatlas/tx.go
index 09cbc57..1f5bc6e 100644
--- a/pkg/blockatlas/tx.go
+++ b/pkg/blockatlas/tx.go
@@ -265,6 +265,9 @@ func (t *Tx) GetAddresses() []string {
 }
 
 func (t *Tx) GetTransactionDirection(address string) Direction {
+	if t.Direction != "" {
+		return t.Direction
+	}
 	if len(t.Inputs) > 0 && len(t.Outputs) > 0 {
 		addressSet := mapset.NewSet(address)
 		return InferDirection(t, addressSet)


Test patch:
diff --git a/api/middleware/cache_test.go b/api/middleware/cache_test.go
index 72d0aaf..70b680b 100644
--- a/api/middleware/cache_test.go
+++ b/api/middleware/cache_test.go
@@ -78,7 +78,7 @@ func TestCacheControl(t *testing.T) {
 	w2 := performRequest("GET", "/cache_ping_control", router)
 	w2CacheControl := w2.Header().Get("Cache-Control")
 
-	assert.NotEqual(t, w1CacheControl, w2CacheControl)
+	assert.Equal(t, w1CacheControl, w2CacheControl)
 	assert.Equal(t, w1.Body.String(), w2.Body.String())
 
 	assert.Equal(t, http.StatusOK, w1.Code)
diff --git a/pkg/blockatlas/tx_test.go b/pkg/blockatlas/tx_test.go
index 787e770..5c1462c 100644
--- a/pkg/blockatlas/tx_test.go
+++ b/pkg/blockatlas/tx_test.go
@@ -525,4 +525,8 @@ func TestTx_GetTransactionDirection(t *testing.T) {
 
 	tx.Direction = tx.GetTransactionDirection("0x38d45371993eEc84f38FEDf93C646aA2D2267CEA")
 	assert.Equal(t, Direction("incoming"), tx.Direction)
+
+	tx.Direction = DirectionSelf
+	tx.Direction = tx.GetTransactionDirection("0x38d45371993eEc84f38FEDf93C646aA2D2267CEA")
+	assert.Equal(t, Direction("yourself"), tx.Direction)
 }