Initial step to adding nym-node functional tests

This commit is contained in:
benedettadavico
2023-10-19 12:52:46 +02:00
parent f328f3fa9e
commit 65e35bd2b0
20 changed files with 4019 additions and 0 deletions
+32
View File
@@ -0,0 +1,32 @@
{
"root": true,
"extends": [
"eslint:recommended",
"plugin:@typescript-eslint/eslint-recommended",
"plugin:@typescript-eslint/recommended",
"plugin:prettier/recommended"
],
"parser": "@typescript-eslint/parser",
"plugins": [
"@typescript-eslint"
],
"rules": {
"import/extensions": "off",
"no-console": ["warn", { "allow": ["warn", "error"] }],
"import/prefer-default-export": "off",
"prettier/prettier": ["error"]
},
"overrides": [
{
"files": ["**/*.ts", "**/*.tsx"],
"rules": {
"@typescript-eslint/explicit-function-return-type": "off",
"@typescript-eslint/explicit-module-boundary-types": "off",
"@typescript-eslint/no-explicit-any": "off",
"no-shadow": "off",
"@typescript-eslint/no-shadow": ["error"]
}
}
]
}
+6
View File
@@ -0,0 +1,6 @@
node_modules
dist
coverage/
.DS_Store
.idea/
junit.xml
@@ -0,0 +1,67 @@
import Gateway from "../../src/endpoints/Gateways";
import { getGatewayIPAddresses } from "../../src/helpers/helper";
describe("Get gateway related info", (): void => {
let contract: Gateway;
let gatewayHosts: string[];
beforeAll(async (): Promise<void> => {
try {
gatewayHosts = await getGatewayIPAddresses();
// console.log(gatewayHosts);
} catch (error) {
throw new Error(`Error fetching gateway IP addresses: ${error.message}`);
}
});
beforeEach(async (): Promise<void> => {
for (let i = 0; i < gatewayHosts.length; i++) {
// console.log("currently trying gateway host", gatewayHosts[i]);
contract = new Gateway(gatewayHosts[i]);
}
});
// TODO this test is failing, it's incorrectly entering the else statement
it("Get root gateway information", async (): Promise<void> => {
const response = await contract.getGatewayInformation();
console.log(response)
console.log(response.wireguard)
if (response.wireguard === null) {
console.log("This is the code I should be entering............")
expect(response.wireguard).toBeNull();
expect(typeof response.mixnet_websockets.ws_port).toBe("number");
expect(typeof response.mixnet_websockets.wss_port).toBe("number");
return;
} else {
console.log("This is wrong, I shouldn't be in the else statement.........")
console.log(response.wireguard);
expect(typeof response.wireguard.port).toBe("number");
expect(typeof response.wireguard.public_key).toBe("string");
expect(typeof response.mixnet_websockets.ws_port).toBe("number");
expect(typeof response.mixnet_websockets.wss_port).toBe("number");
}
});
it("Get client interfaces supported by gateway", async (): Promise<void> => {
const response = await contract.getGatewayClientInterfaces();
if (response.wireguard === null) {
expect(response.wireguard).toBeNull();
} else {
expect(typeof response.wireguard.port).toBe("number");
expect(typeof response.wireguard.public_key).toBe("string");
expect(typeof response.mixnet_websockets.ws_port).toBe("number");
expect(typeof response.mixnet_websockets.wss_port).toBe("number");
}
});
it("Get mixnet websocket info", async (): Promise<void> => {
const response = await contract.getMixnetWebsocketInfo();
expect(typeof response.ws_port).toBe("number");
expect(typeof response.wss_port === ("number") || response.wss_port === null).toBe(true);
});
// it("Get wireguard info", async (): Promise<void> => {
// const response = await contract.getWireguardInfo();
// expect(typeof response.port).toBe("number");
// expect(typeof response.public_key).toBe("string");
// });
});
@@ -0,0 +1,28 @@
// import Mixnode from "../../src/endpoints/Mixnodes";
// import { getGatewayIPAddresses } from '../../src/helpers/helper';
// describe("Get mixnode related info", (): void => {
// let contract: Mixnode;
// let gatewayHosts: string[];
// beforeAll(async (): Promise<void> => {
// try {
// gatewayHosts = await getGatewayIPAddresses();
// console.log(gatewayHosts)
// } catch (error) {
// throw new Error(`Error fetching gateway IP addresses: ${error.message}`);
// }
// });
// beforeEach(async (): Promise<void> => {
// for (let i = 0; i < gatewayHosts.length; i++) {
// console.log("currently trying gateway host", gatewayHosts[i])
// contract = new Mixnode(gatewayHosts[i]);
// }
// });
// it("Get mixnode details", async (): Promise<void> => {
// const response = await contract.getMixnodeInfo();
// // TODO implement checks here
// });
// });
@@ -0,0 +1,54 @@
import Nodes from "../../src/endpoints/Node";
import { getGatewayIPAddresses } from "../../src/helpers/helper";
describe("Get Node information", (): void => {
let contract: Nodes;
let gatewayHosts: string[];
beforeAll(async (): Promise<void> => {
try {
gatewayHosts = await getGatewayIPAddresses();
// console.log(gatewayHosts);
} catch (error) {
throw new Error(`Error fetching gateway IP addresses: ${error.message}`);
}
});
beforeEach(async (): Promise<void> => {
for (let i = 0; i < gatewayHosts.length; i++) {
// console.log("currently trying gateway host", gatewayHosts[i]);
contract = new Nodes(gatewayHosts[i]);
}
});
it("Get build data for the binary running the API", async (): Promise<void> => {
const response = await contract.getBuildInformation();
expect(typeof response.binary_name).toBe("string");
expect(typeof response.build_timestamp).toBe("string");
expect(typeof response.build_version).toBe("string");
expect(typeof response.cargo_profile).toBe("string");
expect(typeof response.commit_branch).toBe("string");
expect(typeof response.commit_sha).toBe("string");
expect(typeof response.commit_timestamp).toBe("string");
expect(typeof response.rustc_channel).toBe("string");
expect(typeof response.rustc_version).toBe("string");
});
it("Get host information for the node", async (): Promise<void> => {
const response = await contract.getHostInformation();
response.data.ip_address.forEach((x) => {
expect(typeof x).toBe("string");
});
// expect(typeof response.data.hostname).toBe("string" || "null");
expect(typeof response.data.hostname === "string" || response.data.hostname === null).toBe(true);
expect(typeof response.data.keys.ed25519).toBe("string");
expect(typeof response.data.keys.x25519).toBe("string");
expect(typeof response.signature).toBe("string");
});
it("Get roles supported by the node", async (): Promise<void> => {
const response = await contract.getSupportedRoles();
expect(typeof response.gateway_enabled).toBe("boolean");
expect(typeof response.mixnode_enabled).toBe("boolean");
expect(typeof response.network_requester_enabled).toBe("boolean");
});
});
+6
View File
@@ -0,0 +1,6 @@
module.exports = {
preset: "ts-jest",
testEnvironment: "node",
reporters: ["default", "jest-junit"],
collectCoverageFrom: ["src/**/*.ts"],
};
+50
View File
@@ -0,0 +1,50 @@
{
"name": "nym-node-test-suite",
"version": "1.0.0",
"description": "a basic nym-node-api suite to test the nym-node-api",
"main": "dist/index.js",
"directories": {
"test": "test"
},
"scripts": {
"test:sandbox": "TEST_ENV=sandbox jest --forceExit --detectOpenHandles --passWithNoTests",
"test:prod": "TEST_ENV=prod jest --forceExit --detectOpenHandles --passWithNoTests",
"build": "tsc",
"lint": "eslint --fix --ext .js,.ts,.tsx .",
"cleanup": "rm -rf node_modules; rm -rf dist; yarn install"
},
"author": "Nymtech",
"license": "MIT",
"files": [
"dist"
],
"engines": {
"node": "18.1.0",
"npm": "8.x"
},
"dependencies": {
"axios": "^0.27.2",
"eslint": "^8.51.0",
"form-data": "4.0.0",
"json-stringify-safe": "5.0.1",
"tslog": "3.3.3",
"uuid": "8.3.2",
"yaml": "^2.2.2"
},
"devDependencies": {
"@types/jest": "^29.5.5",
"@types/node": "^20.8.4",
"@typescript-eslint/eslint-plugin": "^5.12.1",
"@typescript-eslint/parser": "^5.33.0",
"axios-mock-adapter": "^1.20.0",
"eslint-config-prettier": "^9.0.0",
"eslint-plugin-prettier": "^5.0.1",
"jest": "^28.1.3",
"jest-junit": "^14.0.0",
"prettier": "^3.0.3",
"process": "0.11.10",
"ts-jest": "28.0.7",
"typescript": "^4.7.4",
"uuidv4": "^6.2.12"
}
}
+12
View File
@@ -0,0 +1,12 @@
common:
request_headers:
Accept: application/json
Content-Type: application/json
sandbox:
api_base_url: https://sandbox-nym-api1.nymtech.net/api/v1
log_level: error
time_zone: utc
prod:
api_base_url: https://validator.nymtech.net/api/v1
log_level: error
time_zone: utc
@@ -0,0 +1,73 @@
import { readFileSync } from "fs";
import { TLogLevelName } from "tslog";
import YAML from "yaml";
class ConfigHandler {
private static instance: ConfigHandler;
private validEnvironments = ["sandbox", "prod"];
public commonConfig: { request_headers: object };
private currentEnvironment: string;
public environment: string;
public environmentConfig: {
log_level: TLogLevelName;
time_zone: string;
api_base_url: string;
mix_id: number;
identity_key: string;
gateway_identity: string;
};
private constructor() {
this.setCommonConfig();
this.setEnvironmentConfig(process.env.TEST_ENV || "sandbox" || "prod");
}
public static getInstance(): ConfigHandler {
if (!ConfigHandler.instance) {
ConfigHandler.instance = new ConfigHandler();
}
return ConfigHandler.instance;
}
private setCommonConfig(): void {
try {
this.commonConfig = YAML.parse(
readFileSync("src/config/config.yaml", "utf8"),
).common;
} catch (error) {
throw Error(`Error reading common config: (${error})`);
}
}
private setEnvironmentConfig(environment: string): void {
this.ensureEnvironmentIsValid(environment);
try {
this.environmentConfig = YAML.parse(
readFileSync("src/config/config.yaml", "utf8"),
)[environment];
} catch (error) {
throw Error(`Error reading environment config: (${error})`);
}
}
public getEnvironmentConfig(environment: string): any {
return (
this.environmentConfig ||
YAML.parse(readFileSync("src/config/config.yaml", "utf8"))[environment]
);
}
private ensureEnvironmentIsValid(environment: string): void {
if (this.validEnvironments.indexOf(environment) === -1) {
throw Error(`Config environment is not valid: "${environment}"`);
}
}
}
export default ConfigHandler;
+40
View File
@@ -0,0 +1,40 @@
import {
ClientInterfaces,
MixnetWebsockets,
Wireguard,
} from "../types/GatewayTypes";
import { APIClient } from "./abstracts/APIClient";
export default class Gateway extends APIClient {
constructor(baseUrl: string) {
super(baseUrl, "/");
}
public async getGatewayInformation(): Promise<ClientInterfaces> {
const response = await this.restClient.sendGet({
route: `gateway`,
});
return response.data;
}
public async getGatewayClientInterfaces(): Promise<ClientInterfaces> {
const response = await this.restClient.sendGet({
route: `gateway/client-interfaces`,
});
return response.data;
}
public async getMixnetWebsocketInfo(): Promise<MixnetWebsockets> {
const response = await this.restClient.sendGet({
route: `gateway/client-interfaces/mixnet-websockets`,
});
return response.data;
}
public async getWireguardInfo(): Promise<Wireguard> {
const response = await this.restClient.sendGet({
route: `gateway/client-interfaces/wireguard`,
});
return response.data;
}
}
+15
View File
@@ -0,0 +1,15 @@
// import { Mixnodes } from "../types/MixnodeTypes";
// import { APIClient } from "./abstracts/APIClient";
// export default class Mixnode extends APIClient {
// constructor(baseUrl: string) {
// super(baseUrl, "/");
// }
// public async getMixnodeInfo(): Promise<Mixnodes> {
// const response = await this.restClient.sendGet({
// route: `mixnode`,
// });
// return response.data;
// }
// }
+29
View File
@@ -0,0 +1,29 @@
import { BuildInformation, HostInformation, Roles } from "../types/NodeTypes";
import { APIClient } from "./abstracts/APIClient";
export default class Nodes extends APIClient {
constructor(baseUrl: string) {
super(baseUrl, "/");
}
public async getBuildInformation(): Promise<BuildInformation> {
const response = await this.restClient.sendGet({
route: `build-information`,
});
return response.data;
}
public async getHostInformation(): Promise<HostInformation> {
const response = await this.restClient.sendGet({
route: `host-information`,
});
return response.data;
}
public async getSupportedRoles(): Promise<Roles> {
const response = await this.restClient.sendGet({
route: `roles`,
});
return response.data;
}
}
@@ -0,0 +1,29 @@
import { Logger } from "tslog";
import ConfigHandler from "../../config/configHandler";
import { RestClient } from "../../restClient/RestClient";
export abstract class APIClient {
protected constructor(baseUrl: string, serviceUrl: string) {
this.url = baseUrl + serviceUrl;
this.restClient = new RestClient(this.url);
this.serviceName = this.constructor.toString().match(/\w+/g)[1];
this.log.info(`The Service URL for ${this.serviceName} is ${this.url}`);
}
public createdItemIds: Set<string> = new Set();
protected config = ConfigHandler.getInstance();
protected log: Logger = new Logger({
minLevel: this.config.environmentConfig.log_level,
dateTimeTimezone:
this.config.environmentConfig.time_zone ||
Intl.DateTimeFormat().resolvedOptions().timeZone,
});
protected url: string;
public restClient: RestClient;
protected serviceName: string;
}
+28
View File
@@ -0,0 +1,28 @@
import axios from "axios";
import ConfigHandler from "../config/configHandler";
// Get the current env from configHandler
const configHandler = ConfigHandler.getInstance();
const currentEnvironment = process.env.TEST_ENV || "sandbox" || "prod";
const apiBaseUrl =
configHandler.getEnvironmentConfig(currentEnvironment).api_base_url;
// get the gateway ip addresses
export async function getGatewayIPAddresses(): Promise<string[]> {
try {
const response = await axios.get(`${apiBaseUrl}/gateways`);
if (response.status === 200) {
const hosts = response.data.map((item: { gateway: { host: string } }) => {
const host = item.gateway.host;
const apiUrl = `http://${host}:8080/api/v1`;
// console.log(`API URL for host ${host}: ${apiUrl}`);
return apiUrl;
});
return hosts;
} else {
throw new Error("Failed to fetch gateway hosts.");
}
} catch (error) {
throw new Error(`Error fetching gateway IP addresses: ${error.message}`);
}
}
+243
View File
@@ -0,0 +1,243 @@
import axios, {
AxiosInstance,
AxiosRequestConfig,
AxiosResponse,
Method,
} from "axios";
import { Logger } from "tslog";
import { stringify } from "yaml";
import https from "https";
import ConfigHandler from "../config/configHandler";
const config = ConfigHandler.getInstance();
const log = new Logger({
minLevel: config.environmentConfig.log_level,
dateTimeTimezone:
config.environmentConfig.time_zone ||
Intl.DateTimeFormat().resolvedOptions().timeZone,
});
function isSet(property): boolean {
return property !== undefined && property !== null;
}
export class RestClient {
private static authToken: string;
private axiosInstance: AxiosInstance;
constructor(baseUrl: string) {
this.axiosInstance = axios.create({ baseURL: baseUrl });
}
private httpsAgent = new https.Agent({
rejectUnauthorized: false,
});
// Not returning an actual auth token for this example project.
// Just showing how it can be done!
static async getToken(requestHeaders: object) {
requestHeaders["Authorization"] = `asdf`;
}
public async callEndpoint({
route,
method,
authToken,
headers,
data,
additionalConfigs,
params,
}: IAxiosCallEndpointArgs): Promise<AxiosResponse> {
let response;
let responseLog = "Response: ";
let requestHeaders = headers;
// if headers are not passed in, use the default headers
if (requestHeaders == undefined) {
requestHeaders = { ...config.commonConfig.request_headers };
}
// if authToken is passed in, add it to the request headers
if (authToken !== undefined) {
requestHeaders = {
...requestHeaders,
...{
Authorization: `Bearer ${authToken}`,
},
};
}
// if we have not set the auth headers yet, set them
else if (!requestHeaders.Authorization) {
await RestClient.getToken(requestHeaders);
}
log.debug(
RestClient.prepareLogRecord({
route,
method,
headers: requestHeaders,
data,
additionalConfigs,
params,
}),
);
await this.axiosInstance
.request({
url: route,
method,
data,
headers: requestHeaders,
httpsAgent: this.httpsAgent,
params,
...additionalConfigs,
})
.then((res) => {
response = res;
responseLog = `<Success> Status = ${res.status} ${res.statusText}`;
})
.catch((error) => {
response = error.response;
if (response === undefined)
responseLog = `<Error> Something wrong happened, did not get proper error from server! (${error.message})`;
else
responseLog = `<Error> Status = ${response.status} ${response.statusText}, ${error.message}`;
});
log.debug(responseLog);
return response;
}
public async sendPost({
route,
authToken,
data,
params,
headers,
additionalConfigs,
}: IAxiosHttpRequestArgs): Promise<any> {
return this.callEndpoint({
route,
method: "POST",
authToken,
data,
params,
headers,
additionalConfigs,
});
}
public async sendGet({
route,
authToken,
params,
headers,
additionalConfigs,
}: IAxiosHttpRequestArgs): Promise<any> {
return this.callEndpoint({
route,
method: "GET",
authToken,
params,
headers,
additionalConfigs,
});
}
public async sendDelete({
route,
authToken,
params,
headers,
additionalConfigs,
}: IAxiosHttpRequestArgs): Promise<any> {
return this.callEndpoint({
route,
method: "DELETE",
authToken,
params,
headers,
additionalConfigs,
});
}
public async sendPatch({
route,
authToken,
data,
headers,
additionalConfigs,
}: IAxiosHttpRequestArgs): Promise<any> {
return this.callEndpoint({
route,
method: "PATCH",
authToken,
data,
headers,
additionalConfigs,
});
}
public async sendPut({
route,
authToken,
data,
headers,
additionalConfigs,
}: IAxiosHttpRequestArgs): Promise<any> {
return this.callEndpoint({
route,
method: "PUT",
authToken,
data,
headers,
additionalConfigs,
});
}
private static prepareLogRecord({
route,
method,
headers,
data,
additionalConfigs,
params,
}: IAxiosCallEndpointArgs): string {
let logRecord = `Request: ${method} ${route}`;
if (isSet(headers))
logRecord = `${logRecord}\nHeaders: ${stringify(headers)}`;
if (isSet(params)) logRecord = `${logRecord}\nParams: ${stringify(params)}`;
if (isSet(additionalConfigs)) {
logRecord = `${logRecord}\nAdditional Configuration: ${stringify(
additionalConfigs,
)}`;
}
if (isSet(data)) {
const jsonData = stringify(data);
// We don't want to log anything that isn't json data
logRecord = `${logRecord}\nData: ${
jsonData === undefined ? "Some data, not JSON!" : jsonData
}`;
}
return logRecord;
}
}
export interface IAxiosHttpRequestArgs {
route: string;
authToken?: string;
data?: object;
params?: object;
headers?: any;
additionalConfigs?: AxiosRequestConfig;
}
export interface IAxiosCallEndpointArgs extends IAxiosHttpRequestArgs {
method: Method;
}
+14
View File
@@ -0,0 +1,14 @@
export interface ClientInterfaces {
mixnet_websockets: MixnetWebsockets;
wireguard: Wireguard;
}
export interface MixnetWebsockets {
ws_port: number | null;
wss_port: number | null;
}
export interface Wireguard {
port: number | null;
public_key: string;
}
+1
View File
@@ -0,0 +1 @@
// export interface Mixnodes {}
+33
View File
@@ -0,0 +1,33 @@
export interface BuildInformation {
binary_name: string;
build_timestamp: string;
build_version: string;
cargo_profile: string;
commit_branch: string;
commit_sha: string;
commit_timestamp: string;
rustc_channel: string;
rustc_version: string;
}
export interface HostInformation {
data: Data;
signature: string;
}
export interface Data {
hostname: string | null;
ip_address: string[];
keys: Keys;
}
export interface Keys {
ed25519: string;
x25519: string;
}
export interface Roles {
gateway_enabled: boolean;
mixnode_enabled: boolean;
network_requester_enabled: boolean;
}
+25
View File
@@ -0,0 +1,25 @@
{
"compilerOptions": {
"removeComments": true,
"allowJs": true,
"preserveConstEnums": true,
"module": "commonjs",
"target": "ES2019",
"declaration": true,
"esModuleInterop": true,
"sourceMap": true,
"lib": ["esnext"],
"outDir": "dist",
"resolveJsonModule": true,
"moduleResolution": "node",
"allowSyntheticDefaultImports": true,
"paths": {
"*": ["types/*"]
},
"baseUrl": "./",
"typeRoots": ["node_modules/@types"],
"alwaysStrict": true
},
"include": ["src/**/*", "tests/functional_test/*/*"],
"exclude": ["unit_test/**/*"]
}
File diff suppressed because it is too large Load Diff