If you are using GitKraken Client with SSH Key to connect to this gitlab, please read this: https://about.gitlab.com/blog/2021/10/11/notice-for-gitkraken-users-with-gitlab/

Commit 36dedaac authored by MarioWerner's avatar MarioWerner
Browse files
parents 1f5070f4 975779e3
const MetricService = require('../service/metric-service');
const path = require('path');
describe("generateSourcePaths()", () => {
it("should return a list with valid js sources", () => {
let taggedSources = generateTaggedSources();
const metricService = new MetricService();
const result = metricService.generateSourcePaths(taggedSources);
const currentPath = __dirname;
const expectedResult = [path.join(currentPath, '../example', 'test2/test2.js'), path.join(__dirname, '../example', 'testAsDirectory.js/test3.js')];
expect(result).toEqual(expectedResult);
});
});
describe("analyzeSoftwareTags()", () => {
it("should return an empty object when tags array is empty", async () => {
const metricService = new MetricService();
const result = await metricService.analyzeSoftwareTags({projectName :"test", tags: []});
expect(result).toEqual({});
});
it("should return an empty object when tags do not exist", async () => {
const metricService = new MetricService();
const result = await metricService.analyzeSoftwareTags({projectName :"test"});
expect(result).toEqual({});
});
it("should return a report", async () => {
// ToDo
});
});
function generateTaggedSources() {
return {
"path": "../example",
"files": ['testFileWithMin.min.js@1.0.0', 'test2/test2.js@1.0.0', 'testAsDirectory.js/test3.js@1.0.0']
}
}
const MetricService = require('../../service/metric-service');
const RedisService = require('../../service/redis-service');
const datamodel = require ("../../models/result");
const escResultMapper = require ("../../mapper/esc-result-mapper");
const logger = require('../../config/logger');
......@@ -19,9 +19,8 @@ module.exports.analyze = function (request, response) {
metricService.analyzeProject(projectName).then(report => {
logger.info("Finished analyzing. Returning message to response");
//var resultDTO = datamodel(report);
//logger.verbose(report);
response.status(200).json(report);
var resultDTO = escResultMapper(report);
response.status(200).json(resultDTO);
}).catch(error => {
console.log(error)
logger.error("Failed analyzing:", error);
......
// For a detailed explanation regarding each configuration property, visit:
// https://jestjs.io/docs/en/configuration.html
module.exports = {
// All imported modules in your tests should be mocked automatically
// automock: false,
// Stop running tests after `n` failures
// bail: 0,
// The directory where Jest should store its cached dependency information
// cacheDirectory: "C:\\Users\\Giuseppe\\AppData\\Local\\Temp\\jest",
// Automatically clear mock calls and instances between every test
clearMocks: true,
// Indicates whether the coverage information should be collected while executing the test
// collectCoverage: false,
// An array of glob patterns indicating a set of files for which coverage information should be collected
// collectCoverageFrom: undefined,
// The directory where Jest should output its coverage files
coverageDirectory: "coverage",
// An array of regexp pattern strings used to skip coverage collection
// coveragePathIgnorePatterns: [
// "\\\\node_modules\\\\"
// ],
// A list of reporter names that Jest uses when writing coverage reports
// coverageReporters: [
// "json",
// "text",
// "lcov",
// "clover"
// ],
// An object that configures minimum threshold enforcement for coverage results
// coverageThreshold: undefined,
// A path to a custom dependency extractor
// dependencyExtractor: undefined,
// Make calling deprecated APIs throw helpful error messages
// errorOnDeprecated: false,
// Force coverage collection from ignored files using an array of glob patterns
// forceCoverageMatch: [],
// A path to a module which exports an async function that is triggered once before all test suites
// globalSetup: undefined,
// A path to a module which exports an async function that is triggered once after all test suites
// globalTeardown: undefined,
// A set of global variables that need to be available in all test environments
// globals: {},
// The maximum amount of workers used to run your tests. Can be specified as % or a number. E.g. maxWorkers: 10% will use 10% of your CPU amount + 1 as the maximum worker number. maxWorkers: 2 will use a maximum of 2 workers.
// maxWorkers: "50%",
// An array of directory names to be searched recursively up from the requiring module's location
moduleDirectories: [
"node_modules"
],
// An array of file extensions your modules use
// moduleFileExtensions: [
// "js",
// "json",
// "jsx",
// "ts",
// "tsx",
// "node"
// ],
// A map from regular expressions to module names or to arrays of module names that allow to stub out resources with a single module
// moduleNameMapper: {},
// An array of regexp pattern strings, matched against all module paths before considered 'visible' to the module loader
// modulePathIgnorePatterns: [],
// Activates notifications for test results
// notify: false,
// An enum that specifies notification mode. Requires { notify: true }
// notifyMode: "failure-change",
// A preset that is used as a base for Jest's configuration
// preset: undefined,
// Run tests from one or more projects
// projects: undefined,
// Use this configuration option to add custom reporters to Jest
// reporters: undefined,
// Automatically reset mock state between every test
// resetMocks: false,
// Reset the module registry before running each individual test
// resetModules: false,
// A path to a custom resolver
// resolver: undefined,
// Automatically restore mock state between every test
// restoreMocks: false,
// The root directory that Jest should scan for tests and modules within
// rootDir: undefined,
// A list of paths to directories that Jest should use to search for files in
// roots: [
// "<rootDir>"
// ],
// Allows you to use a custom runner instead of Jest's default test runner
// runner: "jest-runner",
// The paths to modules that run some code to configure or set up the testing environment before each test
// setupFiles: [],
// A list of paths to modules that run some code to configure or set up the testing framework before each test
// setupFilesAfterEnv: [],
// A list of paths to snapshot serializer modules Jest should use for snapshot testing
// snapshotSerializers: [],
// The test environment that will be used for testing
testEnvironment: "node",
// Options that will be passed to the testEnvironment
// testEnvironmentOptions: {},
// Adds a location field to test results
// testLocationInResults: false,
// The glob patterns Jest uses to detect test files
// testMatch: [
// "**/__tests__/**/*.[jt]s?(x)",
// "**/?(*.)+(spec|test).[tj]s?(x)"
// ],
// An array of regexp pattern strings that are matched against all test paths, matched tests are skipped
// testPathIgnorePatterns: [
// "\\\\node_modules\\\\"
// ],
// The regexp pattern or array of patterns that Jest uses to detect test files
// testRegex: [],
// This option allows the use of a custom results processor
// testResultsProcessor: undefined,
// This option allows use of a custom test runner
// testRunner: "jasmine2",
// This option sets the URL for the jsdom environment. It is reflected in properties such as location.href
// testURL: "http://localhost",
// Setting this value to "fake" allows the use of fake timers for functions such as "setTimeout"
// timers: "real",
// A map from regular expressions to paths to transformers
// transform: undefined,
// An array of regexp pattern strings that are matched against all source file paths, matched files will skip transformation
// transformIgnorePatterns: [
// "\\\\node_modules\\\\"
// ],
// An array of regexp pattern strings that are matched against all modules before the module loader will automatically return a mock for them
// unmockedModulePathPatterns: undefined,
// Indicates whether each individual test should be reported during the run
// verbose: undefined,
// An array of regexp patterns that are matched against all source file paths before re-running tests in watch mode
// watchPathIgnorePatterns: [],
// Whether to use watchman for file crawling
// watchman: true,
};
/*
* Data Transfer Model for the anlysis result containing the software metrics
*/
const logger = require('../config/logger');
const Result = require('../models/result');
const FileMetric = require('../models/file-metric');
const Halstead = require('../models/halstead');
const localPath = '/usr/src/app/workdir';
function mapToDto(metrics) {
var resultDTO = [];
try {
metrics.forEach(tag => {
var tagMetrics = mapToVersionedResult(tag);
resultDTO.push(tagMetrics);
});
} catch (error){
logger.error("Failed Create the Report in result.js", error);
}
logger.info("Report succesfully created");
return resultDTO;
}
function mapToVersionedResult(tag) {
var result = new Result();
// Set version of versionized project
result.version = tag.tag;
for (var i = 0; i < tag.result.reports.length; i++) {
var metricResult = new FileMetric();
var moduleMetrics = tag.result.reports[i];
metricResult.mcabe = moduleMetrics["aggregate"]["cyclomatic"];
metricResult.loc = moduleMetrics["aggregate"]["sloc"]["logical"];
metricResult.fco = moduleMetrics["aggregate"]["halstead"]["length"]; // ToDo check if correct
metricResult.nom = moduleMetrics["aggregate"]["halstead"]["length"]; // ToDo Check if correct
metricResult.nov = 0; // ToDo missing, where to get?
metricResult.halstead = new Halstead();
metricResult.halstead.bugs = moduleMetrics["aggregate"]["halstead"]["bugs"];
metricResult.halstead.difficulty = moduleMetrics["aggregate"]["halstead"]["difficulty"];;
metricResult.halstead.effort = moduleMetrics["aggregate"]["halstead"]["effort"];
metricResult.halstead.length = moduleMetrics["aggregate"]["halstead"]["length"];
metricResult.halstead.time = moduleMetrics["aggregate"]["halstead"]["time"];
metricResult.halstead.volume = moduleMetrics["aggregate"]["halstead"]["volume"];
metricResult.filename = moduleMetrics["path"].replace(localPath, ""); // We do not want the local path
result.metrics.push(metricResult);
}
return result;
}
module.exports = mapToDto;
const http = require("http");
var options = {
path: '/api/analyze',
port: 8081,
method: 'POST',
headers: { 'Content-Type': 'application/json' }
}
var str;
function GetJSON(callback) {
var req = http.request(options, function (res) {
var test = http.request.chunk;
console.log(test);
res.on('data', function (chunk) {
str += chunk;
});
res.on('end', function()
{
callback(str);
})
});
req.end();
}
module.exports = GetJSON;
\ No newline at end of file
class FileMetric {
constructor() {
this.filename = '';
this.mcabe = 0;
this.loc = 0;
this.fco = 0;
this.nom = 0;
this.nov = 0;
this.halstead = {};
}
}
module.exports = FileMetric;
class Halstead {
constructor() {
this.bugs = 0;
this.difficulty = 0;
this.effort = 0;
this.length = 0;
this.time = 0;
this.volume = 0;
}
}
module.exports = Halstead;
/*
* Data Transfer Model for the anlysis result containing the software metrics
*/
//const GetJSON = require("./JSON_From_Esocomplex.js");
//const GetJSON = require("C:\\Users\\Lenovo\\Desktop\\GetJSON.js");
const logger = require('../config/logger');
var JSON_File = "";
var functionCount = 0;
var FilesInAnalysedProject = [];
// Todo test marc
class DataModel {
//Defined Metrics for our Model
version;
fileName = "";
functionCount_metric = 0;
linesOfCode_metric = 0;
numberOfVariables_metric = 0;
complexity_metric = 0;
numerOfMethods_metric = 0;
//Halstead Parameters
halsteadLength = 0;
halsteadVolume = 0;
halsteadDifficulty = 0;
halsteadEffort = 0;
halsteadTime = 0;
halsteadBugs = 0;
//File-Parameters
fileName = "";
filepath = "";
}
function convertToDto(metrics) {
try {
metrics.forEach(elem => {
element = elem;
var dto = EsoToDataModel(metrics, element);
ConvertDataModelToJSON(dto);
});
logger.info("Report succesfully created");
logger.info("Filestructure: \n" + FilesInAnalysedProject)
return FilesInAnalysedProject;
} catch{
logger.error("Failed Create the Report in result.js");
class Result {
constructor() {
this.version = '';
this.metrics = []
}
}
function EsoToDataModel(data, element) {
var dto = new DataModel();
dto.version = element.tag;
dto.complexity_metric = element.result["reports"][0]["aggregate"]["cyclomatic"];
dto.linesOfCode_metric = element.result["reports"][0]["aggregate"]["sloc"]["logical"];
var phyLOC = element.result["reports"][0]["aggregate"]["sloc"]["physical"];
dto.numerOfMethods_metric = element.result["reports"][0]["aggregate"]["halstead"]["length"];;
//What is FunctionCount exactly?
functionCount += dto.numerOfMethods_metric;
//Isnt available in Esocomplex JSON;
dto.numberOfVariables_metric = 0;
dto.halsteadBugs = element.result["reports"][0]["aggregate"]["halstead"]["bugs"];;
dto.halsteadDifficulty = element.result["reports"][0]["aggregate"]["halstead"]["difficulty"];;
dto.halsteadEffort = element.result["reports"][0]["aggregate"]["halstead"]["effort"];
dto.halsteadLength = element.result["reports"][0]["aggregate"]["halstead"]["length"];
dto.halsteadTime = element.result["reports"][0]["aggregate"]["halstead"]["time"];
dto.halsteadVolume = element.result["reports"][0]["aggregate"]["halstead"]["volume"];
dto.filepath = element.result["reports"][0]["path"];
return dto;
}
function ConvertDataModelToJSON(data) {
JSON_File = StringifyJSON(data);
FilesInAnalysedProject.push(JSON_File);
}
function StringifyJSON(data) {
//console.log(data);
json_m = JSON.stringify({
Filename: data.fileName,
Metrics:
{
MCCabe: data.complexity_metric,
FCO: data.functionCount_metric,
LOC: data.linesOfCode_metric,
NOV: data.numberOfVariables_metric,
NOM: data.numerOfMethods_metric,
Halstead:
{
Length: data.halsteadLength,
Volume: data.halsteadVolume,
Difficulty: data.halsteadDifficulty,
Effort: data.halsteadEffort,
Time: data.halsteadTime,
Bugs: data.halsteadBugs
}
}
});
return json_m;
}
module.exports = convertToDto;
module.exports = Result;
......@@ -4,7 +4,7 @@
"description": "",
"main": "server.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"test": "jest",
"start": "node server.js",
"dev": "nodemon ./src/server.js"
},
......@@ -13,6 +13,7 @@
"dependencies": {
"body-parser": "^1.19.0",
"check-types": "^11.1.2",
"escomplex": "^2.0.0-alpha",
"esprima": "^4.0.1",
"express": "^4.17.1",
"fs-extra": "^9.0.1",
......@@ -21,7 +22,9 @@
"nodemon": "^2.0.4",
"redis": "^3.0.2",
"rimraf": "^3.0.2",
"escomplex": "^2.0.0-alpha",
"winston": "^3.2.1"
},
"devDependencies": {
"jest": "^26.0.1"
}
}
......@@ -69,7 +69,8 @@ class MetricService {
logger.info(`Finished analysing project with name ${project.projectName} and tag ${tag}`);
report.push({"tag": tag, "result": result});
};
}
return report;
}
......@@ -140,7 +141,6 @@ class MetricService {
var stat = fs.statSync(files[i]);
if (!stat.isDirectory() && !files[i].includes(".min")) {
//logger.debug("test: ",files[i])
sources.push({"path": files[i], "code": fs.readFileSync(files[i]).toString('utf-8')});
}
}
......
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment