Skip to content

Commit

Permalink
feat(test enhancements): enhance (#241)
Browse files Browse the repository at this point in the history
* feat(test enhancements): enhance

* fix(report): report

* fix(fix): failing test

* fix(fix): test

* fix(fix): issue

* fix(fix): coverage threshold

* fix(fix): number

* fix(fix): last steps

* fix(fix): sonarqube

* fix(rem test.ts from calc): calc

* fix(rem): test
  • Loading branch information
cgilbe27 authored Oct 13, 2023
1 parent 11c9782 commit f9e55f7
Show file tree
Hide file tree
Showing 12 changed files with 11,520 additions and 11,886 deletions.
49 changes: 0 additions & 49 deletions .github/workflows/test-indexer-nibi.yaml

This file was deleted.

Original file line number Diff line number Diff line change
@@ -1,49 +1,66 @@
name: ⛓️ Tests @nibiruchain/nibijs
name: ⛓️ Tests @nibiruchain/ts-sdk

on:
pull_request:
branches: ["main", "releases/*"]
branches: ["releases/*"]
paths: ["**.js", "**.ts", "**.tsx", "**.json"]
push:
branches: ["main", "releases/*"]
branches: ["releases/*"]
paths: ["**.js", "**.ts", "**.tsx", "**.json"]

jobs:
test-nibijs:
runs-on: ubuntu-latest
env:
CHAIN_HOST: ${{ secrets.CHAIN_HOST }}
VALIDATOR_MNEMONIC: ${{ secrets.VALIDATOR_MNEMONIC }}
VALIDATOR_ADDRESS: ${{ secrets.VALIDATOR_ADDRESS }}
LCD_ENDPOINT: "http://127.0.0.1:1317"
GRPC_ENDPOINT: "127.0.0.1:9090"
TENDERMINT_RPC_ENDPOINT: "http://127.0.0.1:26657"
USE_LOCALNET: true
WEBSOCKET_ENDPOINT: "ws://127.0.0.1:26657/websocket"
CHAIN_ID: "nibiru-localnet-0"
VALIDATOR_MNEMONIC: "guard cream sadness conduct invite crumble clock pudding hole grit liar hotel maid produce squeeze return argue turtle know drive eight casino maze host"
steps:
- name: Check out the repo
uses: actions/checkout@v3
with:
fetch-depth: 0 # Shallow clones should be disabled for a better relevancy of analysis

- name: Install nibid
run: curl -s https://get.nibiru.fi/@v0.21.9! | bash
# Use https://get.nibiru.fi/ to get the most recent release.

- name: Check nibid version
run: nibid version

- name: Run localnet.sh in the background
run: |
sh scripts/localnet.sh &
- name: Setup NodeJS and npm
uses: actions/setup-node@v3
with:
node-version: "lts/hydrogen"
- name: Install yarn using npm
run: npm install -g yarn
- name: Setup NodeJS with yarn caching
uses: actions/setup-node@v3
with:
node-version: "lts/hydrogen"
cache: "yarn"

- name: Install yarn using npm
run: npm install -g yarn

- name: Install dependencies
run: yarn --prefer-offline --check-files

- name: Build the application
run: yarn build --include-dependencies || yarn build --parallel --include-dependencies
- name: Run tests - nibijs
run: yarn test:nibijs

- name: Run tests
run: yarn test

- name: Jest Coverage Comment
uses: MishaKav/jest-coverage-comment@main

- name: SonarCloud Scan
uses: SonarSource/sonarcloud-github-action@master
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} # Needed to get PR information, if any
SONAR_TOKEN: ${{ secrets.SONAR_TOKEN }}
2 changes: 1 addition & 1 deletion LICENSE
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
MIT License

Copyright (c) 2022 @NibiruChain
Copyright (c) @NibiruChain

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
Expand Down
26 changes: 17 additions & 9 deletions jest.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -22,27 +22,35 @@ module.exports = function (root = __dirname) {
// clearMocks: false,

// Indicates whether the coverage information should be collected while executing the test
// collectCoverage: true,
collectCoverage: true,

// An array of glob patterns indicating a set of files for which coverage information should be collected
// collectCoverageFrom: null,
collectCoverageFrom: [
"packages/indexer-nibi/src/**/*.{js,jsx,ts,tsx}",
"packages/nibijs/src/**/*.{js,jsx,ts,tsx}",
"!**/node_modules/**",
"!**/dist/**",
],

// The directory where Jest should output its coverage files
// coverageDirectory: null,

// An array of regexp pattern strings used to skip coverage collection
coveragePathIgnorePatterns: [
"/node_modules/",
"<rootDir>/dist/",
"protojs/dist/",
],
coveragePathIgnorePatterns: ["/node_modules/", "/dist/"],

// A list of reporter names that Jest uses when writing coverage reports
// coverageReporters: ['json', 'html', 'lcov', 'text'],
coverageReporters: ["json", "text"],
coverageReporters: ["json-summary", "text", "html", "lcov"],

// An object that configures minimum threshold enforcement for coverage results
// coverageThreshold: null,
coverageThreshold: {
global: {
branches: 50,
functions: 50,
lines: 50,
statements: 50,
},
},

// A path to a custom dependency extractor
// dependencyExtractor: null,
Expand Down
6 changes: 1 addition & 5 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -18,11 +18,7 @@
"clean": "lerna run --parallel clean",
"commit": "cz",
"publish:all": "lerna publish from-package",
"test": "jest",
"test:short": "jest --testPathIgnorePatterns faucet.test.ts",
"test:nibijs": "yarn test --verbose --coverage --testPathPattern=packages/nibijs --testPathIgnorePatterns faucet.test.ts",
"test:indexer-nibi": "yarn test --verbose --coverage --testPathPattern=packages/indexer-nibi",
"coverage": "jest --coverage",
"test": "jest --verbose",
"lint": "eslint -c './.eslintrc.js' './packages/**/*.{ts,js}'",
"lint:ci": "yarn lint . --format junit",
"lint:md": "markdownlint --ignore node_modules --ignore .git",
Expand Down
4 changes: 2 additions & 2 deletions packages/indexer-nibi/src/heart-monitor.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,9 +12,9 @@ const nibiruUrl = "itn-3"

const heartMonitor = new HeartMonitor(
{
endptTm: `https://hm-graphql.${nibiruUrl}.nibiru.fi`,
endptTm: `https://hm-graphql.${nibiruUrl}.nibiru.fi/query`,
},
`ws://hm-graphql.${nibiruUrl}.nibiru.fi`
`wss://hm-graphql.${nibiruUrl}.nibiru.fi/query`
)

describe("Heart Monitor constructor", () => {
Expand Down
13 changes: 0 additions & 13 deletions packages/indexer-nibi/src/node-test.ts

This file was deleted.

2 changes: 1 addition & 1 deletion packages/nibijs/docs/classes/StableSwap.md
Original file line number Diff line number Diff line change
Expand Up @@ -178,7 +178,7 @@ y()
Calculate x[j] if one makes x[i] = x

Done by solving quadratic equation iteratively.
x*1**2 + x1 * (sum' - (A*n**n - 1) * D / (A _ n**n)) = D ** (n+1)/(n \*\* (2 _ n) \_ prod' \* A)
x*1\*\*2 + x1 * (sum' - (A*n\*\*n - 1) * D / (A _ n**n)) = D ** (n+1)/(n \*\* (2 _ n) \_ prod' \* A)
x_1\*\*2 + b\*x_1 = c

x_1 = (x_1\**2 + c) / (2*x_1 + b)
Expand Down
27 changes: 13 additions & 14 deletions packages/nibijs/src/chain/useFaucet.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { Chain, ChainIdParts, chainToParts } from "./chain"
import { fetch } from "cross-fetch"
import { Chain, chainToParts } from "./chain"

/**
* Sends 11 NIBI, 100 NUSD, and 100 USDT to the given address from the testnet faucet.
Expand Down Expand Up @@ -38,19 +39,17 @@ export async function useFaucet({
`
)

return window
.fetch(faucetUrl, {
method: "POST",
headers: {
Accept: "application/json",
"Content-Type": "application/json",
},
body: JSON.stringify({ address, coins, grecaptcha }),
})
.catch((err) => {
console.error(err)
throw err
})
return fetch(faucetUrl, {
method: "POST",
headers: {
Accept: "application/json",
"Content-Type": "application/json",
},
body: JSON.stringify({ address, coins, grecaptcha }),
}).catch((err) => {
console.error(err)
throw err
})
}

/**
Expand Down
35 changes: 16 additions & 19 deletions packages/nibijs/src/test/faucet.test.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { assertIsDeliverTxSuccess, DeliverTxResponse } from "@cosmjs/stargate"
import { fetch } from "cross-fetch"
import {
Chain,
faucetUrlFromChain,
Expand All @@ -14,6 +15,10 @@ import {
} from "../tx"
import { TEST_CHAIN, TEST_MNEMONIC } from "./helpers"

jest.mock("cross-fetch", () => ({
fetch: jest.fn().mockImplementation(() => ({ catch: jest.fn() })),
}))

// We can't create a test token even with faked recaptcha site
// and secret tokens. This not only would require a setup to generate
// a token from the UI, but to also create a fake backend
Expand Down Expand Up @@ -63,27 +68,21 @@ describe("useFaucet", () => {
endptTm: "",
endptRest: "",
endptGrpc: "",
chainId: "prefix-shortName-1",
chainId: "nibiru-itn-3",
chainName: "",
feeDenom: "",
}

const grecaptcha = "TEST_GRECAPTCHA_TOKEN"
const address = "0x1234567890"
const expectedUrl = "https://faucet.shortName-1.nibiru.fi/"
const mockedFetch = jest.fn(
() =>
Promise.resolve({
json: () => Promise.resolve({}),
}) as unknown as Promise<Response>
)
const expectedUrl = "https://faucet.itn-3.nibiru.fi/"

test("should request funds from faucet with default amounts", async () => {
await useFaucet({ address, chain, grecaptcha })

const expectedCoins = ["11000000unibi", "100000000unusd", "100000000uusdt"]

expect(mockedFetch).toHaveBeenCalledWith(expectedUrl, {
expect(fetch).toHaveBeenCalledWith(expectedUrl, {
method: "POST",
headers: {
Accept: "application/json",
Expand All @@ -99,7 +98,7 @@ describe("useFaucet", () => {

const expectedCoins = ["5000000unibi", "50000000unusd", "50000000uusdt"]

expect(mockedFetch).toHaveBeenCalledWith(expectedUrl, {
expect(fetch).toHaveBeenCalledWith(expectedUrl, {
method: "POST",
headers: {
Accept: "application/json",
Expand All @@ -111,14 +110,12 @@ describe("useFaucet", () => {

test("should throw an error if fetch fails", async () => {
const errorMessage = "Failed to fetch"
const mockedFetchError = jest
.fn()
.mockImplementationOnce(() => Promise.reject(new Error(errorMessage)))

await expect(useFaucet({ address, chain, grecaptcha })).rejects.toThrow(
errorMessage
)
expect(mockedFetchError).toHaveBeenCalledTimes(1)

jest.mock("cross-fetch", () => ({
fetch: jest.fn().mockRejectedValueOnce(new Error(errorMessage)),
}))

expect(await useFaucet({ address, chain, grecaptcha })).toEqual(undefined)
})

test("faucetUrlFromChain helper func should construct faucet URL from chain object", () => {
Expand All @@ -127,7 +124,7 @@ describe("useFaucet", () => {
endptTm: "",
endptRest: "",
endptGrpc: "",
chainId: "prefix-shortName-1",
chainId: "nibiru-itn-3",
chainName: "",
feeDenom: "",
})
Expand Down
16 changes: 16 additions & 0 deletions sonar-project.properties
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
sonar.projectKey=NibiruChain_ts-sdk
sonar.organization=nibiruchain

sonar.javascript.lcov.reportPaths=./coverage/lcov.info
sonar.coverage.exclusions=**/*.test.ts

# This is the name and version displayed in the SonarCloud UI.
#sonar.projectName=ts-sdk
#sonar.projectVersion=1.0


# Path is relative to the sonar-project.properties file. Replace "\" by "/" on Windows.
#sonar.sources=.

# Encoding of the source code. Default is default system encoding
#sonar.sourceEncoding=UTF-8
Loading

1 comment on commit f9e55f7

@github-actions
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Lines Statements Branches Functions
Coverage: 82%
83.01% (1217/1466) 55.05% (376/683) 71.91% (251/349)

Please sign in to comment.