Skip to content

Commit 315dbdf

Browse files
committed
Issue #118: Add tests-integration/node-channel
Add an integration test for node-channel. The test starts a simple node express server,which uses the logging setup using NodeChannel. Then in the /test route it will log a line. We use k6 for performance testing, which calls the endpoint 10.000 times by 4 virtual CPU's as fast as it can. Then we verify the log files, to see that what we expect is present.
1 parent 29f736c commit 315dbdf

File tree

7 files changed

+276
-0
lines changed

7 files changed

+276
-0
lines changed
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
# Logs
2+
logs
3+
*.log
4+
npm-debug.log*
5+
yarn-debug.log*
6+
yarn-error.log*
7+
pnpm-debug.log*
8+
lerna-debug.log*
9+
10+
node_modules
11+
dist
12+
dist-ssr
13+
*.local
14+
k6
15+
16+
# Editor directories and files
17+
.vscode/*
18+
!.vscode/extensions.json
19+
.idea
20+
.DS_Store
21+
*.suo
22+
*.ntvs*
23+
*.njsproj
24+
*.sln
25+
*.sw?
Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
{
2+
"name": "node-channel",
3+
"private": true,
4+
"version": "0.0.0",
5+
"type": "module",
6+
"main": "dist/main.js",
7+
"scripts": {
8+
"clean": "shx rm -rf ./dist",
9+
"build": "npm run clean && tsc && npm run test",
10+
"k6": "./k6/k6 run ./src/test/k6-test.js && node dist/test/node-verify.js",
11+
"start": "node dist/main/main.js",
12+
"test": "start-server-and-test start http://localhost:3000 k6"
13+
},
14+
"dependencies": {
15+
"express": "4.19.2",
16+
"typescript-logging": "file:../../core/dist/typescript-logging-2.2.0.tgz",
17+
"typescript-logging-category-style": "file:../../category-style/dist/typescript-logging-category-style-2.2.0.tgz",
18+
"typescript-logging-node-channel": "file:../../node-channel/dist/typescript-logging-node-channel-2.2.0.tgz"
19+
},
20+
"devDependencies": {
21+
"@types/express": "4.17.21",
22+
"@types/node": "20.12.6",
23+
"typescript": "5.2.2",
24+
"start-server-and-test": "2.0.3",
25+
"shx": "0.3.4"
26+
}
27+
}
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
import {LogLevel} from "typescript-logging";
2+
import {Category, CategoryProvider} from "typescript-logging-category-style";
3+
import {NodeChannelFactory} from "typescript-logging-node-channel";
4+
5+
const channel = NodeChannelFactory.createLogChannel(
6+
NodeChannelFactory.createRetentionStrategyMaxFiles({
7+
directory: "dist/log",
8+
maxFileSize: {unit: "KiloBytes", value: 512},
9+
maxFiles: 5
10+
})
11+
);
12+
13+
const provider = CategoryProvider.createProvider("TestProvider", {
14+
level: LogLevel.Info,
15+
channel
16+
});
17+
18+
export function getLogger(name: string): Category {
19+
return provider.getCategory(name);
20+
}
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
import express, {Express, Request, Response} from "express";
2+
import {getLogger} from "./config/LogConfig.js";
3+
4+
const app: Express = express();
5+
const port = process.env.PORT || 3000;
6+
7+
const log = getLogger("main.ts");
8+
9+
let counter = 0;
10+
11+
app.get("/", (req: Request, res: Response) => {
12+
res.send("Some nice output");
13+
});
14+
15+
app.get("/test", (req: Request, res: Response) => {
16+
counter++;
17+
const localCount = counter.toString(10).padStart(6, '0');
18+
log.info(() => `This is a logging message for testing purposes only, we are counting the messages. This is message ${localCount}`);
19+
20+
res.send(`Did write message ${localCount}`);
21+
});
22+
23+
app.listen(port, () => {
24+
console.log(`[server]: Server is running at http://localhost:${port}`);
25+
});
Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
import http from 'k6/http';
2+
import {check} from 'k6';
3+
4+
export const options = {
5+
vus: 4,
6+
iterations: 10000
7+
};
8+
export default function () {
9+
const res = http.get('http://localhost:3000/test');
10+
check(res, {'status was 200': (r) => r.status == 200});
11+
}
Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
/* This is a node file, so it must be run with node. */
2+
3+
import fs from "fs";
4+
import os from "os";
5+
6+
function readFileLines(path: string) {
7+
if (!fs.existsSync(path)) {
8+
throw new Error(`Failed to find ${path}`);
9+
}
10+
11+
const allFileContents = fs.readFileSync(path, 'utf-8');
12+
const lines = allFileContents.split(os.EOL);
13+
// Remove last empty line (that is the newline)
14+
return lines.slice(0, lines.length-1);
15+
}
16+
17+
function verifyLines(lines: string[], expectedLineCount: number, lineFrom: number) {
18+
if (lines.length !== expectedLineCount) {
19+
throw new Error(`Expected ${expectedLineCount} lines, but got ${lines.length}`);
20+
}
21+
for (let i = 0; i < expectedLineCount; i++) {
22+
const expectedEndsWithLine = `This is message ${(lineFrom + i).toString(10).padStart(6, "0")}`;
23+
const line = lines[i];
24+
if (!line.endsWith(expectedEndsWithLine)) {
25+
throw new Error(`Line '${lineFrom + i}' does not end with '${expectedEndsWithLine}', got line: '${line}'`);
26+
}
27+
}
28+
}
29+
30+
console.log("Verifying log files...");
31+
32+
const logDir = `${process.cwd()}/dist/log`;
33+
34+
/* Verify we have 3 log files, with a total of 10000 lines each line nicely numbered incrementing by 1. */
35+
const path1 = `${logDir}/application1.log`;
36+
const path2 = `${logDir}/application2.log`;
37+
const path3 = `${logDir}/application3.log`;
38+
39+
let lines = readFileLines(path1);
40+
verifyLines(lines, 3591, 1);
41+
42+
lines = readFileLines(path2);
43+
verifyLines(lines, 3591, 3592);
44+
45+
lines = readFileLines(path3);
46+
verifyLines(lines, 2818, 7183);
47+
48+
console.log("Verification complete.");
Lines changed: 120 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,120 @@
1+
{
2+
"compilerOptions": {
3+
/* Visit https://aka.ms/tsconfig to read more about this file */
4+
5+
/* Projects */
6+
// "incremental": true, /* Save .tsbuildinfo files to allow for incremental compilation of projects. */
7+
// "composite": true, /* Enable constraints that allow a TypeScript project to be used with project references. */
8+
// "tsBuildInfoFile": "./.tsbuildinfo", /* Specify the path to .tsbuildinfo incremental compilation file. */
9+
// "disableSourceOfProjectReferenceRedirect": true, /* Disable preferring source files instead of declaration files when referencing composite projects. */
10+
// "disableSolutionSearching": true, /* Opt a project out of multi-project reference checking when editing. */
11+
// "disableReferencedProjectLoad": true, /* Reduce the number of projects loaded automatically by TypeScript. */
12+
13+
/* Language and Environment */
14+
"target": "ES2020",
15+
/* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */
16+
// "lib": [], /* Specify a set of bundled library declaration files that describe the target runtime environment. */
17+
// "jsx": "preserve", /* Specify what JSX code is generated. */
18+
// "experimentalDecorators": true, /* Enable experimental support for legacy experimental decorators. */
19+
// "emitDecoratorMetadata": true, /* Emit design-type metadata for decorated declarations in source files. */
20+
// "jsxFactory": "", /* Specify the JSX factory function used when targeting React JSX emit, e.g. 'React.createElement' or 'h'. */
21+
// "jsxFragmentFactory": "", /* Specify the JSX Fragment reference used for fragments when targeting React JSX emit e.g. 'React.Fragment' or 'Fragment'. */
22+
// "jsxImportSource": "", /* Specify module specifier used to import the JSX factory functions when using 'jsx: react-jsx*'. */
23+
// "reactNamespace": "", /* Specify the object invoked for 'createElement'. This only applies when targeting 'react' JSX emit. */
24+
// "noLib": true, /* Disable including any library files, including the default lib.d.ts. */
25+
// "useDefineForClassFields": true, /* Emit ECMAScript-standard-compliant class fields. */
26+
// "moduleDetection": "auto", /* Control what method is used to detect module-format JS files. */
27+
28+
/* Modules */
29+
"module": "Node16",
30+
/* Specify what module code is generated. */
31+
// "rootDir": "./", /* Specify the root folder within your source files. */
32+
// "moduleResolution": "node10", /* Specify how TypeScript looks up a file from a given module specifier. */
33+
"moduleResolution": "Node16",
34+
// "baseUrl": "./", /* Specify the base directory to resolve non-relative module names. */
35+
// "paths": {}, /* Specify a set of entries that re-map imports to additional lookup locations. */
36+
// "rootDirs": [], /* Allow multiple folders to be treated as one when resolving modules. */
37+
// "typeRoots": [], /* Specify multiple folders that act like './node_modules/@types'. */
38+
// "types": [], /* Specify type package names to be included without being referenced in a source file. */
39+
// "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */
40+
// "moduleSuffixes": [], /* List of file name suffixes to search when resolving a module. */
41+
// "allowImportingTsExtensions": true, /* Allow imports to include TypeScript file extensions. Requires '--moduleResolution bundler' and either '--noEmit' or '--emitDeclarationOnly' to be set. */
42+
// "resolvePackageJsonExports": true, /* Use the package.json 'exports' field when resolving package imports. */
43+
// "resolvePackageJsonImports": true, /* Use the package.json 'imports' field when resolving imports. */
44+
// "customConditions": [], /* Conditions to set in addition to the resolver-specific defaults when resolving imports. */
45+
// "resolveJsonModule": true, /* Enable importing .json files. */
46+
// "allowArbitraryExtensions": true, /* Enable importing files with any extension, provided a declaration file is present. */
47+
// "noResolve": true, /* Disallow 'import's, 'require's or '<reference>'s from expanding the number of files TypeScript should add to a project. */
48+
49+
/* JavaScript Support */
50+
// "allowJs": true, /* Allow JavaScript files to be a part of your program. Use the 'checkJS' option to get errors from these files. */
51+
// "checkJs": true, /* Enable error reporting in type-checked JavaScript files. */
52+
// "maxNodeModuleJsDepth": 1, /* Specify the maximum folder depth used for checking JavaScript files from 'node_modules'. Only applicable with 'allowJs'. */
53+
54+
/* Emit */
55+
// "declaration": true, /* Generate .d.ts files from TypeScript and JavaScript files in your project. */
56+
// "declarationMap": true, /* Create sourcemaps for d.ts files. */
57+
// "emitDeclarationOnly": true, /* Only output d.ts files and not JavaScript files. */
58+
// "sourceMap": true, /* Create source map files for emitted JavaScript files. */
59+
// "inlineSourceMap": true, /* Include sourcemap files inside the emitted JavaScript. */
60+
// "outFile": "./", /* Specify a file that bundles all outputs into one JavaScript file. If 'declaration' is true, also designates a file that bundles all .d.ts output. */
61+
// "outDir": "./", /* Specify an output folder for all emitted files. */
62+
"outDir": "./dist",
63+
// "removeComments": true, /* Disable emitting comments. */
64+
// "noEmit": true, /* Disable emitting files from a compilation. */
65+
// "importHelpers": true, /* Allow importing helper functions from tslib once per project, instead of including them per-file. */
66+
// "importsNotUsedAsValues": "remove", /* Specify emit/checking behavior for imports that are only used for types. */
67+
// "downlevelIteration": true, /* Emit more compliant, but verbose and less performant JavaScript for iteration. */
68+
// "sourceRoot": "", /* Specify the root path for debuggers to find the reference source code. */
69+
// "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */
70+
// "inlineSources": true, /* Include source code in the sourcemaps inside the emitted JavaScript. */
71+
// "emitBOM": true, /* Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files. */
72+
// "newLine": "crlf", /* Set the newline character for emitting files. */
73+
// "stripInternal": true, /* Disable emitting declarations that have '@internal' in their JSDoc comments. */
74+
// "noEmitHelpers": true, /* Disable generating custom helper functions like '__extends' in compiled output. */
75+
// "noEmitOnError": true, /* Disable emitting files if any type checking errors are reported. */
76+
// "preserveConstEnums": true, /* Disable erasing 'const enum' declarations in generated code. */
77+
// "declarationDir": "./", /* Specify the output directory for generated declaration files. */
78+
// "preserveValueImports": true, /* Preserve unused imported values in the JavaScript output that would otherwise be removed. */
79+
80+
/* Interop Constraints */
81+
// "isolatedModules": true, /* Ensure that each file can be safely transpiled without relying on other imports. */
82+
// "verbatimModuleSyntax": true, /* Do not transform or elide any imports or exports not marked as type-only, ensuring they are written in the output file's format based on the 'module' setting. */
83+
// "allowSyntheticDefaultImports": true, /* Allow 'import x from y' when a module doesn't have a default export. */
84+
"esModuleInterop": true,
85+
/* Emit additional JavaScript to ease support for importing CommonJS modules. This enables 'allowSyntheticDefaultImports' for type compatibility. */
86+
// "preserveSymlinks": true, /* Disable resolving symlinks to their realpath. This correlates to the same flag in node. */
87+
"forceConsistentCasingInFileNames": true,
88+
/* Ensure that casing is correct in imports. */
89+
90+
/* Type Checking */
91+
"strict": true,
92+
/* Enable all strict type-checking options. */
93+
// "noImplicitAny": true, /* Enable error reporting for expressions and declarations with an implied 'any' type. */
94+
// "strictNullChecks": true, /* When type checking, take into account 'null' and 'undefined'. */
95+
// "strictFunctionTypes": true, /* When assigning functions, check to ensure parameters and the return values are subtype-compatible. */
96+
// "strictBindCallApply": true, /* Check that the arguments for 'bind', 'call', and 'apply' methods match the original function. */
97+
// "strictPropertyInitialization": true, /* Check for class properties that are declared but not set in the constructor. */
98+
// "noImplicitThis": true, /* Enable error reporting when 'this' is given the type 'any'. */
99+
// "useUnknownInCatchVariables": true, /* Default catch clause variables as 'unknown' instead of 'any'. */
100+
// "alwaysStrict": true, /* Ensure 'use strict' is always emitted. */
101+
// "noUnusedLocals": true, /* Enable error reporting when local variables aren't read. */
102+
// "noUnusedParameters": true, /* Raise an error when a function parameter isn't read. */
103+
// "exactOptionalPropertyTypes": true, /* Interpret optional property types as written, rather than adding 'undefined'. */
104+
// "noImplicitReturns": true, /* Enable error reporting for codepaths that do not explicitly return in a function. */
105+
// "noFallthroughCasesInSwitch": true, /* Enable error reporting for fallthrough cases in switch statements. */
106+
// "noUncheckedIndexedAccess": true, /* Add 'undefined' to a type when accessed using an index. */
107+
// "noImplicitOverride": true, /* Ensure overriding members in derived classes are marked with an override modifier. */
108+
// "noPropertyAccessFromIndexSignature": true, /* Enforces using indexed accessors for keys declared using an indexed type. */
109+
// "allowUnusedLabels": true, /* Disable error reporting for unused labels. */
110+
// "allowUnreachableCode": true, /* Disable error reporting for unreachable code. */
111+
112+
/* Completeness */
113+
// "skipDefaultLibCheck": true, /* Skip type checking .d.ts files that are included with TypeScript. */
114+
"skipLibCheck": true
115+
/* Skip type checking all .d.ts files. */
116+
},
117+
"include": [
118+
"./src/**/*"
119+
]
120+
}

0 commit comments

Comments
 (0)