How to use byTestKey method in stryker-parent

Best JavaScript code snippet using stryker-parent

incremental-differ.ts

Source:incremental-differ.ts Github

copy

Full Screen

1import path from 'path';2import { diff_match_patch as DiffMatchPatch } from 'diff-match-patch';3import chalk from 'chalk';4import { schema, Mutant, Position, Location, MutantStatus, StrykerOptions, FileDescriptions, MutateDescription } from '@stryker-mutator/api/core';5import { Logger } from '@stryker-mutator/api/logging';6import { TestResult, TestStatus } from '@stryker-mutator/api/test-runner';7import { I, normalizeFileName, normalizeLineEndings, notEmpty } from '@stryker-mutator/util';8import { TestDefinition } from 'mutation-testing-report-schema';9import { commonTokens } from '@stryker-mutator/api/plugin';10import { DiffChange, DiffStatisticsCollector } from './diff-statistics-collector.js';11import { TestCoverage } from './test-coverage.js';12/**13 * The 'diff match patch' high-performant 'diffing' of files.14 * @see https://github.com/google/diff-match-patch15 */16const diffMatchPatch = new DiffMatchPatch();17/**18 * This class is responsible for calculating the diff between a run and a previous run based on the incremental report.19 *20 * Since the ids of tests and mutants can differ across reports (they are only unique within 1 report), this class21 * identifies mutants and tests by attributes that make them unique:22 * - Mutant: file name, mutator name, location and replacement23 * - Test: test name, test file name (if present) and location (if present).24 *25 * We're storing these identifiers in local variables (maps and sets) as strings.26 * We should move to 'records' for these when they come available: https://github.com/tc39/proposal-record-tuple27 *28 * A mutant result from the previous run is reused if the following conditions were met:29 * - The location of the mutant refers to a piece of code that didn't change30 * - If mutant was killed:31 * - The culprit test wasn't changed32 * - If the mutant survived:33 * - No test was added34 *35 * It uses google's "diff-match-patch" project to calculate the new locations for tests and mutants, see link.36 * @link https://github.com/google/diff-match-patch37 */38export class IncrementalDiffer {39 public mutantStatisticsCollector: DiffStatisticsCollector | undefined;40 public testStatisticsCollector: DiffStatisticsCollector | undefined;41 private readonly mutateDescriptionByRelativeFileName: Map<string, MutateDescription>;42 public static inject = [commonTokens.logger, commonTokens.options, commonTokens.fileDescriptions] as const;43 constructor(private readonly logger: Logger, private readonly options: StrykerOptions, fileDescriptions: FileDescriptions) {44 this.mutateDescriptionByRelativeFileName = new Map(45 Object.entries(fileDescriptions).map(([name, description]) => [toRelativeNormalizedFileName(name), description.mutate])46 );47 }48 private isInMutatedScope(relativeFileName: string, mutant: schema.MutantResult): boolean {49 const mutate = this.mutateDescriptionByRelativeFileName.get(relativeFileName);50 return mutate === true || (Array.isArray(mutate) && mutate.some((range) => locationIncluded(range, mutant.location)));51 }52 public diff(53 currentMutants: readonly Mutant[],54 testCoverage: I<TestCoverage>,55 incrementalReport: schema.MutationTestResult,56 currentRelativeFiles: Map<string, string>57 ): readonly Mutant[] {58 const { files, testFiles } = incrementalReport;59 const mutantStatisticsCollector = new DiffStatisticsCollector();60 const testStatisticsCollector = new DiffStatisticsCollector();61 // Expose the collectors for unit testing purposes62 this.mutantStatisticsCollector = mutantStatisticsCollector;63 this.testStatisticsCollector = testStatisticsCollector;64 // Collect what we can reuse, while correcting for diff in the locations65 const reusableMutantsByKey = collectReusableMutantsByKey(this.logger);66 const { byId: oldTestsById, byKey: oldTestInfoByKey } = collectReusableTestInfo(this.logger);67 // Collect some helper maps and sets68 const { oldCoverageByMutantKey: oldCoverageTestKeysByMutantKey, oldKilledByMutantKey: oldKilledTestKeysByMutantKey } =69 collectOldKilledAndCoverageMatrix();70 const oldTestKeys = new Set([...oldTestsById.values()].map(({ key }) => key));71 const newTestKeys = new Set(72 [...testCoverage.testsById].map(([, test]) => testToIdentifyingKey(test, toRelativeNormalizedFileName(test.fileName)))73 );74 // Create a dictionary to more easily get test information75 const testInfoByKey = collectCurrentTestInfo();76 // Mark which tests are added77 for (const [key, { relativeFileName }] of testInfoByKey) {78 if (!oldTestKeys.has(key)) {79 testStatisticsCollector.count(relativeFileName, 'added');80 }81 }82 // Make sure that tests that didn't run this time around aren't forgotten83 for (const [84 testKey,85 {86 test: { name, location },87 relativeFileName,88 },89 ] of oldTestInfoByKey) {90 if (!testInfoByKey.has(testKey)) {91 const test: TestResult = {92 status: TestStatus.Success,93 id: testKey,94 name,95 startPosition: location?.start,96 timeSpentMs: 0,97 fileName: path.resolve(relativeFileName),98 };99 testInfoByKey.set(testKey, { test, relativeFileName: relativeFileName });100 testCoverage.addTest(test);101 }102 }103 // Done with preparations, time to map over the mutants104 let reusedMutantCount = 0;105 const currentMutantKeys = new Set<string>();106 const mutants = currentMutants.map((mutant) => {107 const relativeFileName = toRelativeNormalizedFileName(mutant.fileName);108 const mutantKey = mutantToIdentifyingKey(mutant, relativeFileName);109 currentMutantKeys.add(mutantKey);110 if (!mutant.status && !this.options.force) {111 const oldMutant = reusableMutantsByKey.get(mutantKey);112 if (oldMutant) {113 const coveringTests = testCoverage.forMutant(mutant.id);114 const killedByTestKeys = oldKilledTestKeysByMutantKey.get(mutantKey);115 if (mutantCanBeReused(mutant, oldMutant, mutantKey, coveringTests, killedByTestKeys)) {116 reusedMutantCount++;117 const { status, statusReason, testsCompleted } = oldMutant;118 return {119 ...mutant,120 status,121 statusReason,122 testsCompleted,123 coveredBy: [...(coveringTests ?? [])].map(({ id }) => id),124 killedBy: testKeysToId(killedByTestKeys),125 };126 }127 } else {128 mutantStatisticsCollector.count(relativeFileName, 'added');129 }130 }131 return mutant;132 });133 // Make sure that old mutants that didn't run this time around aren't forgotten134 for (const [mutantKey, oldResult] of reusableMutantsByKey) {135 // Do an additional check to see if the mutant is in mutated range.136 //137 // For example:138 // ```diff139 // - return a || b;140 // + return a && b;141 // ```142 // The conditional expression mutator here decides to _not_ mutate b to `false` the second time around. (even though the text of "b" itself didn't change)143 // Not doing this additional check would result in a sticky mutant that is never removed144 if (!currentMutantKeys.has(mutantKey) && !this.isInMutatedScope(oldResult.relativeFileName, oldResult)) {145 const coverage = oldCoverageTestKeysByMutantKey.get(mutantKey) ?? [];146 const killed = oldKilledTestKeysByMutantKey.get(mutantKey) ?? [];147 const coveredBy = testKeysToId(coverage);148 const killedBy = testKeysToId(killed);149 const reusedMutant = {150 ...oldResult,151 id: mutantKey,152 fileName: path.resolve(oldResult.relativeFileName),153 replacement: oldResult.replacement ?? oldResult.mutatorName,154 coveredBy,155 killedBy,156 };157 mutants.push(reusedMutant);158 testCoverage.addCoverage(reusedMutant.id, coveredBy);159 }160 }161 if (this.logger.isInfoEnabled()) {162 const testInfo = testCoverage.hasCoverage ? `\n\tTests:\t\t${testStatisticsCollector.createTotalsReport()}` : '';163 this.logger.info(164 `Incremental report:\n\tMutants:\t${mutantStatisticsCollector.createTotalsReport()}` +165 testInfo +166 `\n\tResult:\t\t${chalk.yellowBright(reusedMutantCount)} of ${currentMutants.length} mutant result(s) are reused.`167 );168 }169 if (this.logger.isDebugEnabled()) {170 const lineSeparator = '\n\t\t';171 const noChanges = 'No changes';172 const detailedMutantSummary = `${lineSeparator}${mutantStatisticsCollector.createDetailedReport().join(lineSeparator) || noChanges}`;173 const detailedTestsSummary = `${lineSeparator}${testStatisticsCollector.createDetailedReport().join(lineSeparator) || noChanges}`;174 this.logger.debug(`Detailed incremental report:\n\tMutants: ${detailedMutantSummary}\n\tTests: ${detailedTestsSummary}`);175 }176 return mutants;177 function testKeysToId(testKeys: Iterable<string> | undefined) {178 return [...(testKeys ?? [])]179 .map((id) => testInfoByKey.get(id))180 .filter(notEmpty)181 .map(({ test: { id } }) => id);182 }183 function collectReusableMutantsByKey(log: Logger) {184 return new Map(185 Object.entries(files).flatMap(([fileName, oldFile]) => {186 const relativeFileName = toRelativeNormalizedFileName(fileName);187 const currentFileSource = currentRelativeFiles.get(relativeFileName);188 if (currentFileSource) {189 log.trace('Diffing %s', relativeFileName);190 const { results, removeCount } = performFileDiff(oldFile.source, currentFileSource, oldFile.mutants);191 mutantStatisticsCollector.count(relativeFileName, 'removed', removeCount);192 return results.map((m) => [193 mutantToIdentifyingKey(m, relativeFileName),194 {195 ...m,196 relativeFileName,197 },198 ]);199 }200 mutantStatisticsCollector.count(relativeFileName, 'removed', oldFile.mutants.length);201 // File has since been deleted, these mutants are not reused202 return [];203 })204 );205 }206 function collectReusableTestInfo(log: Logger) {207 const byId = new Map<string, { relativeFileName: string; test: TestDefinition; key: string }>();208 const byKey = new Map<string, TestInfo>();209 Object.entries(testFiles ?? {}).forEach(([fileName, oldTestFile]) => {210 const relativeFileName = toRelativeNormalizedFileName(fileName);211 const currentFileSource = currentRelativeFiles.get(relativeFileName);212 if (currentFileSource !== undefined && oldTestFile.source !== undefined) {213 log.trace('Diffing %s', relativeFileName);214 const locatedTests = closeLocations(oldTestFile);215 const { results, removeCount } = performFileDiff(oldTestFile.source, currentFileSource, locatedTests);216 testStatisticsCollector.count(relativeFileName, 'removed', removeCount);217 results.forEach((test) => {218 const key = testToIdentifyingKey(test, relativeFileName);219 const testInfo = { key, test, relativeFileName };220 byId.set(test.id, testInfo);221 byKey.set(key, testInfo);222 });223 } else {224 // No sources to compare, we should do our best with the info we do have225 oldTestFile.tests.map((test) => {226 const key = testToIdentifyingKey(test, relativeFileName);227 const testInfo = { key, test, relativeFileName };228 byId.set(test.id, testInfo);229 byKey.set(key, testInfo);230 });231 }232 });233 return { byId, byKey };234 }235 function collectOldKilledAndCoverageMatrix() {236 const oldCoverageByMutantKey = new Map<string, Set<string>>();237 const oldKilledByMutantKey = new Map<string, Set<string>>();238 for (const [key, mutant] of reusableMutantsByKey) {239 const killedRow = new Set(mutant.killedBy?.map((testId) => oldTestsById.get(testId)?.key).filter(notEmpty));240 const coverageRow = new Set(mutant.coveredBy?.map((testId) => oldTestsById.get(testId)?.key).filter(notEmpty));241 killedRow.forEach((killed) => coverageRow.add(killed));242 oldCoverageByMutantKey.set(key, coverageRow);243 oldKilledByMutantKey.set(key, killedRow);244 }245 return { oldCoverageByMutantKey, oldKilledByMutantKey };246 }247 function collectCurrentTestInfo() {248 const byTestKey = new Map<string, { relativeFileName: string; test: TestResult }>();249 for (const testResult of testCoverage.testsById.values()) {250 const relativeFileName = toRelativeNormalizedFileName(testResult.fileName);251 const key = testToIdentifyingKey(testResult, relativeFileName);252 const info = { relativeFileName, test: testResult, key: key };253 byTestKey.set(key, info);254 }255 return byTestKey;256 }257 function mutantCanBeReused(258 mutant: Mutant,259 oldMutant: schema.MutantResult,260 mutantKey: string,261 coveringTests: ReadonlySet<TestResult> | undefined,262 oldKillingTests: Set<string> | undefined263 ): boolean {264 if (!testCoverage.hasCoverage) {265 // This is the best we can do when the test runner didn't report coverage.266 // We assume that all mutant test results can be reused,267 // End users can use --force to force retesting of certain mutants268 return true;269 }270 if (oldMutant.status === MutantStatus.Ignored) {271 // Was previously ignored, but not anymore, we need to run it now272 return false;273 }274 const testsDiff = diffTestCoverage(mutant.id, oldCoverageTestKeysByMutantKey.get(mutantKey), coveringTests);275 if (oldMutant.status === MutantStatus.Killed) {276 if (oldKillingTests) {277 for (const killingTest of oldKillingTests) {278 if (testsDiff.get(killingTest) === 'same') {279 return true;280 }281 }282 }283 // Killing tests has changed or no longer exists284 return false;285 }286 for (const action of testsDiff.values()) {287 if (action === 'added') {288 // A non-killed mutant got a new test, we need to run it289 return false;290 }291 }292 // A non-killed mutant did not get new tests, no need to rerun it293 return true;294 }295 /**296 * Determines if there is a diff between old test coverage and new test coverage.297 */298 function diffTestCoverage(299 mutantId: string,300 oldCoveringTestKeys: Set<string> | undefined,301 newCoveringTests: ReadonlySet<TestResult> | undefined302 ): Map<string, DiffAction> {303 const result = new Map<string, DiffAction>();304 if (newCoveringTests) {305 for (const newTest of newCoveringTests) {306 const key = testToIdentifyingKey(newTest, toRelativeNormalizedFileName(newTest.fileName));307 result.set(key, oldCoveringTestKeys?.has(key) ? 'same' : 'added');308 }309 }310 if (oldCoveringTestKeys) {311 const isStatic = testCoverage.hasStaticCoverage(mutantId);312 for (const oldTestKey of oldCoveringTestKeys) {313 if (!result.has(oldTestKey)) {314 // Static mutants might not have covering tests, but the test might still exist315 if (isStatic && newTestKeys.has(oldTestKey)) {316 result.set(oldTestKey, 'same');317 } else {318 result.set(oldTestKey, 'removed');319 }320 }321 }322 }323 return result;324 }325 }326}327/**328 * Finds the diff of mutants and tests. Removes mutants / tests that no longer exist (changed or removed). Updates locations of mutants or tests that do still exist.329 * @param oldCode The old code to use for the diff330 * @param newCode The new (current) code to use for the diff331 * @param items The mutants or tests to be looked . These will be treated as immutable.332 * @returns A list of items with updated locations, without items that are changed.333 */334function performFileDiff<T extends { location: Location }>(oldCode: string, newCode: string, items: T[]): { results: T[]; removeCount: number } {335 const oldSourceNormalized = normalizeLineEndings(oldCode);336 const currentSrcNormalized = normalizeLineEndings(newCode);337 const diffChanges = diffMatchPatch.diff_main(oldSourceNormalized, currentSrcNormalized);338 const toDo = new Set(items.map((m) => ({ ...m, location: deepClone(m.location) })));339 const [added, removed] = [1, -1];340 const done: T[] = [];341 const currentPosition: Position = { column: 0, line: 0 };342 let removeCount = 0;343 for (const [change, text] of diffChanges) {344 if (toDo.size === 0) {345 // There are more changes, but nothing left to update.346 break;347 }348 const offset = calculateOffset(text);349 if (change === added) {350 for (const test of toDo) {351 const { location } = test;352 if (gte(currentPosition, location.start) && gte(location.end, currentPosition)) {353 // This item cannot be reused, code was added here354 removeCount++;355 toDo.delete(test);356 } else {357 locationAdd(location, offset, currentPosition.line === location.start.line);358 }359 }360 positionMove(currentPosition, offset);361 } else if (change === removed) {362 for (const item of toDo) {363 const {364 location: { start },365 } = item;366 const endOffset = positionMove({ ...currentPosition }, offset);367 if (gte(endOffset, start)) {368 // This item cannot be reused, the code it covers has changed369 removeCount++;370 toDo.delete(item);371 } else {372 locationAdd(item.location, negate(offset), currentPosition.line === start.line);373 }374 }375 } else {376 positionMove(currentPosition, offset);377 toDo.forEach((item) => {378 const { end } = item.location;379 if (gte(currentPosition, end)) {380 // We're done with this item, it can be reused381 toDo.delete(item);382 done.push(item);383 }384 });385 }386 }387 done.push(...toDo);388 return { results: done, removeCount };389}390/**391 * A greater-than-equals implementation for positions392 */393function gte(a: Position, b: Position) {394 return a.line > b.line || (a.line === b.line && a.column >= b.column);395}396function locationIncluded(haystack: Location, needle: Location) {397 const startIncluded = gte(needle.start, haystack.start);398 const endIncluded = gte(haystack.end, needle.end);399 return startIncluded && endIncluded;400}401function deepClone(loc: Location): Location {402 return { start: { ...loc.start }, end: { ...loc.end } };403}404/**405 * Reduces a mutant to a string that identifies the mutant across reports.406 * Consists of the relative file name, mutator name, replacement, and location407 */408function mutantToIdentifyingKey(409 { mutatorName, replacement, location: { start, end } }: Pick<Mutant, 'location' | 'mutatorName'> & { replacement?: string },410 relativeFileName: string411) {412 return `${relativeFileName}@${start.line}:${start.column}-${end.line}:${end.column}\n${mutatorName}: ${replacement}`;413}414function testToIdentifyingKey(415 { name, location, startPosition }: Pick<schema.TestDefinition, 'location' | 'name'> & Pick<TestResult, 'startPosition'>,416 relativeFileName: string | undefined417) {418 startPosition = startPosition ?? location?.start ?? { line: 0, column: 0 };419 return `${relativeFileName}@${startPosition.line}:${startPosition.column}\n${name}`;420}421export function toRelativeNormalizedFileName(fileName: string | undefined): string {422 return normalizeFileName(path.relative(process.cwd(), fileName ?? ''));423}424function calculateOffset(text: string): Position {425 const pos: Position = { line: 0, column: 0 };426 for (const char of text) {427 if (char === '\n') {428 pos.line++;429 pos.column = 0;430 } else {431 pos.column++;432 }433 }434 return pos;435}436function positionMove(pos: Position, diff: Position): Position {437 pos.line += diff.line;438 if (diff.line === 0) {439 pos.column += diff.column;440 } else {441 pos.column = diff.column;442 }443 return pos;444}445function locationAdd({ start, end }: Location, { line, column }: Position, currentLine: boolean) {446 start.line += line;447 if (currentLine) {448 start.column += column;449 }450 end.line += line;451 if (line === 0 && currentLine) {452 end.column += column;453 }454}455function negate({ line, column }: Position): Position {456 return { line: -1 * line, column: -1 * column };457}458interface TestInfo {459 relativeFileName: string;460 test: TestDefinition;461 key: string;462}463type DiffAction = DiffChange | 'same';464/**465 * Sets the end position of each test to the start position of the next test.466 * This is an educated guess and necessary.467 * If a test has no location, it is assumed it spans the entire file (line 0 to Infinity)468 *469 * Knowing the end location of tests is necessary in order to know if the test was changed.470 */471function closeLocations(testFile: schema.TestFile): LocatedTest[] {472 const locatedTests: LocatedTest[] = [];473 const openEndedTests: OpenEndedTest[] = [];474 testFile.tests.forEach((test) => {475 if (testHasLocation(test)) {476 if (isClosed(test)) {477 locatedTests.push(test);478 } else {479 openEndedTests.push(test);480 }481 } else {482 locatedTests.push({ ...test, location: { start: { line: 0, column: 0 }, end: { line: Number.POSITIVE_INFINITY, column: 0 } } });483 }484 });485 if (openEndedTests.length) {486 // Sort the opened tests in order to close their locations487 openEndedTests.sort((a, b) => a.location.start.line - b.location.start.line);488 const startPositions = uniqueStartPositions(openEndedTests);489 let currentPositionIndex = 0;490 let currentPosition = startPositions[currentPositionIndex];491 openEndedTests.forEach((test) => {492 if (currentPosition && test.location.start.line === currentPosition.line && test.location.start.column === currentPosition.column) {493 currentPositionIndex++;494 currentPosition = startPositions[currentPositionIndex];495 }496 if (currentPosition) {497 locatedTests.push({ ...test, location: { start: test.location.start, end: currentPosition } });498 }499 });500 // Don't forget about the last test501 const lastTest = openEndedTests[openEndedTests.length - 1];502 locatedTests.push({ ...lastTest, location: { start: lastTest.location.start, end: { line: Number.POSITIVE_INFINITY, column: 0 } } });503 }504 return locatedTests;505}506/**507 * Determines the unique start positions of a sorted list of tests in order508 */509function uniqueStartPositions(sortedTests: OpenEndedTest[]) {510 let current: Position | undefined;511 const startPositions = sortedTests.reduce<Position[]>((collector, { location: { start } }) => {512 if (!current || current.line !== start.line || current.column !== start.column) {513 current = start;514 collector.push(current);515 }516 return collector;517 }, []);518 return startPositions;519}520function testHasLocation(test: schema.TestDefinition): test is OpenEndedTest {521 return !!test.location?.start;522}523function isClosed(test: Required<schema.TestDefinition>): test is LocatedTest {524 return !!test.location.end;525}526type LocatedTest = schema.TestDefinition & { location: Location };...

Full Screen

Full Screen

tests.js

Source:tests.js Github

copy

Full Screen

1var isAlreadyChecked = false;2var isSelectedAllCheckBox = false;3$(document).ready(function () {4 $('#availableGroups').multiselect({5 includeSelectAllOption: true,6 buttonWidth: 250,7 enableFiltering: true 8 });9 $('.datepicker').datepicker({10 format: "yyyy-mm-dd",11 todayHighlight : true,12 language:'en',13 /* todayBtn: true, */14 clearBtn : true,15 autoclose : true16 });17 $('.datepicker').datepicker('setDate', new Date());18 $('#selectAll').on('click',function(){19 if(!isAlreadyChecked){20 $('.selectQuestionCheckBox').each(function(){21 $(this).prop( "checked", true );22 });23 isAlreadyChecked = true;24 isSelectedAllCheckBox = true;25 }else{26 $('.selectQuestionCheckBox').each(function(){27 $(this).prop( "checked", false );28 });29 isAlreadyChecked = false;30 }31 32 });33 34 $('#summernote').summernote({35 height: 300,36 popover: {37 image: [],38 link: [],39 air: []40 }41 });42 43// getAllTests();44 applyTestsFilter('ON_LOAD');45 getAllGroups();46 47 $('#startOn').datetimepicker();48 $('#endOn').datetimepicker();49 50 //$('#summernote').summernote('code')51 /* $('.note-insert .note-icon-picture').parent().remove(); */52 $('.note-view .note-icon-arrows-alt').parent().remove();53 var navListItems = $('div.setup-panel div a'),54 allWells = $('.setup-content'),55 allNextBtn = $('.nextBtn'),56 allPrevBtn = $('.prevBtn');57 allWells.hide();58 navListItems.click(function (e) {59 e.preventDefault();60 var $target = $($(this).attr('href')),61 $item = $(this);62 if (!$item.hasClass('disabled')) {63 navListItems.removeClass('btn-success').addClass('btn-default');64 $item.addClass('btn-success');65 allWells.hide();66 $target.show();67 }68 });69 allNextBtn.click(function () {70 var curStep = $(this).closest(".setup-content"),71 curStepBtn = curStep.attr("id"),72 nextStepWizard = $('div.setup-panel div a[href="#' + curStepBtn + '"]').parent().next().children("a"),73 curInputs = curStep.find("input[type='text']")74 isValid = true;75 /* $(".form-group").removeClass("has-error");76 for (var i = 0; i < curInputs.length; i++) {77 if (!curInputs[i].validity.valid) {78 isValid = false;79 $(curInputs[i]).closest(".form-group").addClass("has-error");80 }81 }82 */ 83 84 if (isValid) nextStepWizard.removeAttr('disabled').trigger('click');85 });86 87 allPrevBtn.click(function () {88 var curStep = $(this).closest(".setup-content"),89 curStepBtn = curStep.attr("id"),90 nextStepWizard = $('div.setup-panel div a[href="#' + curStepBtn + '"]').parent().prev().children("a"),91 curInputs = curStep.find("input[type='text']"), 92 isValid = true;93 //$(".form-group").removeClass("has-error");94 if (isValid) nextStepWizard.removeAttr('disabled').trigger('click'); 95 });96 $('div.setup-panel div a.btn-success').trigger('click');97});98function randomString() {99 var chars = "";100 chars = chars + "ABCDEFGHIJKLMNOPQRSTUVWXTZ";101 chars = chars + "abcdefghiklmnopqrstuvwxyz"; 102 chars = chars + "0123456789";103 chars = chars + "!#$%&@";104 105 var string_length = 10;106 var randomstring = '';107 for (var i=0; i<string_length; i++) {108 var rnum = Math.floor(Math.random() * chars.length);109 randomstring += chars.substring(rnum,rnum+1);110 }111 console.log(randomstring);112 $('#accessKey').val(randomstring);113}114function getAllGroups(){115 $('#groups-table-body').html('');116 $.ajax({117 type : "POST",118 url : "getAllGroupsInfo",119 success : function(itr) {120 var str = '';121 if (itr.groupList != null && itr.groupList.length > 0) {122 for (var i = 0; i < itr.groupList.length; i++) {123 var groupID = itr.groupList[i].group_id;124 var groupName = itr.groupList[i].group_name;125 str += '<tr id="group-'+groupID+'">'126 +'<td><input type="checkbox" class="selectQuestionCheckBox" value ="'+groupID+'" /></td>'127 +'<td><a href="#" onclick="viewGroupDetails('+groupID+',\''+groupName+'\');">' + groupID + '</a></td>'128 +'<td>'+ groupName + '</td>'129 +'</tr>';130 }131 $('#groups-table-body').append(str);132 }else{133 str += '<div class="text-center"> No record found </div>';134 $('#groups-table-body').append(str);135 }136 },137 error : function(itr) {138 alert("No values found..!!");139 }140 });141}142function createTest(){143 var testName = $('#testName').val();144 var testkey = $('#testkey').val();145 var accessKey = $('#accessKey').val();146 var testInstructionsHtmlCode = $('#summernote').summernote('code');147 var groupIDs = [];148 var hrs = $('#hrs').val();149 var mins = $('#mins').val();150 var secs = $('#secs').val();151 var startOn = '';152 if($('#startOn').val() != ''){153 startOn = $('#startOn').val()+':00';154 }155 var endOn = '';156 if($('#endOn').val() != ''){157 endOn = $('#endOn').val()+':00';158 }159 var passingCriteria = $('#passingCriteria').val();160 if(hrs == ''){161 $('#hrs').val('0');162 }else if(mins == ''){163 $('#mins').val('0');164 }else if(secs == ''){165 $('#secs').val('0');166 }167 $('.selectQuestionCheckBox').each(function(){168 if($(this).prop('checked') == true){169 groupIDs.push($(this).val());170 }171 });172 var data = {173 testName: testName,174 testkey: testkey,175 accessKey: accessKey,176 groupIDs: $('#availableGroups').val(),177 startOn: startOn,178 endOn : endOn,179 hrs : hrs,180 mins : mins,181 secs : secs,182 passingCriteria : passingCriteria,183 testInstructionsHtmlCode: testInstructionsHtmlCode184 };185 $.ajax({186 type : "POST",187 url : "createTest",188 dataType: 'json',189 data: JSON.stringify(data),190 contentType:"application/json;charset=utf-8",191 success : function(itr) {192 if(itr.res != null && (itr.errorMsg == null || itr.errorMsg == '')){193 var status = itr.res.status;194 if(status == 200){195 alert(itr.res.message);196// getAllTests();197 applyTestsFilter('ON_LOAD');198 $('.add-one-more').remove();199 $('#last-step').append('<a href="testsPage" class="btn btn-primary pull-right add-one-more">Add One More</a>');200 }else if(status == 403){201 alert(itr.res.message);202 }203 }else{204 alert(itr.errorMsg);205 }206 },207 error : function(itrr) {208 alert("Error occurred while creating test..!!");209 }210 });211}212function formatDateTime(date) {213 var day = date.getDate();214 var monthIndex = date.getMonth();215 var year = date.getFullYear();216 var min = date.getMinutes();217 var hours = date.getHours();218 var sec = date.getSeconds();219 //return day + ' ' + monthNames[monthIndex] + ' ' + year;220 return year+'-'+monthIndex+'-'+day+' '+hours+':'+min+':'+sec;221 }222function formatMyDate(date) {223 var day = date.getDate();224 var monthIndex = date.getMonth();225 monthIndex = monthIndex +1;226 var year = date.getFullYear();227 return day+'-'+monthIndex+'-'+year;228 }229function getAllTests() {230 $('#tests-table-body').html('');231 $.ajax({232 type : "POST",233 url : "getAllTests",234 success : function(itr) {235 var str = '';236 if (itr.testList != null && itr.testList.length > 0) {237 for (var i = 0; i < itr.testList.length; i++) {238 var testID = itr.testList[i].test_id;239 var testName = itr.testList[i].test_name;240 var testKey = itr.testList[i].test_key;241 var accessKey = itr.testList[i].access_key;242 var isLive = itr.testList[i].is_live;243 var liveRes = '';244 if(isLive == 1){245 liveRes = '<i class="fa fa-hourglass-start text-success"></i>';246 }else{247 liveRes = '<i class="fa fa-hourglass-o text-warning"></i>';248 }249 var createdOn = formatDate(new Date(itr.testList[i].created_on));250 var updatedOn = formatDate(new Date(itr.testList[i].updated_on));251 var createdBy = itr.testList[i].created_by;252 var uddatedBy = itr.testList[i].updated_by;253 str += '<tr id="test-'+testID+'">'254 +'<td>'+testID+'</td>'255 +'<td>'+testName+'</td>'256 +'<td>'+testKey+'</td>'257 +'<td><input type="password" class="access-key-value" id="access-key-'+testID+'" value="'+accessKey+'" /><i class="fa fa-eye" onclick="toggleShow(this,'+testID+');"></i></td>'258 +'<td>'+liveRes+'</td>'259 +'<td>'+createdOn+'</td>'260 +'<td>'+updatedOn+'</td>'261 +'<td>'+createdBy+'</td>'262 +'<td>'+uddatedBy+'</td>'263 +'<td><i class="fa fa-trash text-danger delete" onclick="deleteThisTest('+testID+');"></i>'264 +'<i class="fa fa-pencil text-primary edit" onclick="updateTheTest('+testID+',\''+testName+'\');"></i>'265 +'</td>'266 +'</tr>';267 268 }269 $('#tests-table-body').append(str);270 }else{271 str += '<div class="text-center"> No record found </div>';272 $('#tests-table-body').append(str);273 }274 },275 error : function(itr) {276 alert("No values found..!!");277 }278 });279}280function deleteThisTest(testID){281 $('#deleteModal').modal('show');282 $('#deleteBtn').removeAttr('onclick');283 $('#deleteBtn').attr('onclick','deleteTheTest('+testID+');');284}285function deleteTheTest(testID){286 287 var data = {288 testID: testID289 };290 $.ajax({291 type : "POST",292 url : "deleteTest",293 dataType: 'json',294 data: JSON.stringify(data),295 contentType:"application/json;charset=utf-8",296 success : function(itr) {297 $('#test-'+testID).fadeTo("slow",0.7, function(){298 $(this).remove();299 })300 $('#deleteModal').modal('hide');301 applyTestsFilter('ON_LOAD');302 },303 error : function(itrr) {304 alert("Error occurred while creating test..!!");305 }306 });307}308function updateTheTest(testID,testName){309 localStorage.removeItem("selectedTestName");310 localStorage.setItem("selectedTestName",testName);311 window.location.href = "updateTestPage.action?testID="+testID;312}313function toggleShow(ths, testID){314 if($(ths).hasClass('fa-eye')){315 $('#access-key-'+testID).removeAttr('type');316 $('#access-key-'+testID).attr('type','text');317 $(ths).removeClass('fa-eye');318 $(ths).addClass('fa-eye-slash');319 }else{320 $('#access-key-'+testID).removeAttr('type');321 $('#access-key-'+testID).attr('type','password');322 $(ths).removeClass('fa-eye-slash');323 $(ths).addClass('fa-eye');324 }325}326function applyTestsFilter(flag){327 $('#tests-table-body').html('');328 $('.tests-table-loader').show();329 var testName = $('#byTestName').val();330 var testId = $('#byTestId').val();331 var startDate = '';332 var endDate = ''; 333 var testKey = $('#byTestKey').val();334 if(flag == 'ON_LOAD'){335 startDate = '';336 endDate = ''; 337 }else{338 if($('#startDate').val() != ''){339 startDate = $('#startDate').val() + " 00:00:00";340 }341 if($('#endDate').val() != ''){342 endDate = $('#endDate').val() + " 23:59:00";343 }344 }345 346 var createdBy = $('#createdBy').val();347 348 var data = {349 startDate : startDate,350 endDate : endDate,351 testName : testName.trim(),352 testId : +testId,353 createdBy : createdBy,354 testKey : testKey355 };356 357 $.ajax({358 type : "POST",359 url : "getTestReport",360 data: JSON.stringify(data),361 dataType: 'json',362 contentType:"application/json;charset=utf-8",363 success : function(itr) {364 var str = '';365 if (itr.testList != null && itr.testList.length > 0) {366 if ($.fn.DataTable.isDataTable("#dtable")) {367 $('#dtable').DataTable().clear().destroy();368 }369 for(var i = 0; i < itr.testList.length; i++){370 var testID = itr.testList[i].test_id;371 var testName = itr.testList[i].test_name;372 var testKey = itr.testList[i].test_key;373 var accessKey = itr.testList[i].access_key;374 var isLive = itr.testList[i].is_live;375 var liveRes = '';376 if(isLive == 1){377 liveRes = '<i class="fa fa-hourglass-start text-success"></i>';378 }else{379 liveRes = '<i class="fa fa-hourglass-o text-warning"></i>';380 }381 var createdOn = formatMyDate(new Date(itr.testList[i].created_on));382 var updatedOn = formatMyDate(new Date(itr.testList[i].updated_on));383 var createdBy = itr.testList[i].created_by;384 var uddatedBy = itr.testList[i].updated_by;385 var str = '<tr>';386 str=str+'<td class="text-nowrap"><a href="#" class="test-id" onclick="testDetails(this);" value="'+testID+'">'+testID+'</a></td>';387 str=str+'<td class="text-nowrap">'+testName+'</td>';388 str=str+'<td class="text-nowrap">'+testKey+'</td>';389 str=str+'<td class="text-nowrap"><input type="password" class="access-key-value form-control" id="access-key-'+testID+'" value="'+accessKey+'" /><i class="fa fa-eye" onclick="toggleShow(this,'+testID+');"></i></td>';390// str=str+'<td class="text-nowrap">'+liveRes+'</td>';391 str=str+'<td class="text-nowrap">'+createdOn+'</td>';392 str=str+'<td class="text-nowrap">'+updatedOn+'</td>';393 str=str+'<td class="text-nowrap">'+createdBy+'</td>';394 str=str+'<td class="text-nowrap">'+uddatedBy+'</td>';395 str=str+'<td class="text-nowrap">';396 if(itr.hasTestEditAccess == false && itr.hasTestDeleteAccess == false){397 str=str+'NO ACTION';398 }else{399 if(itr.hasTestDeleteAccess == true)400 str=str+'<i class="fa fa-trash text-danger delete" onclick="deleteThisTest('+testID+');"></i>';401 if(itr.hasTestEditAccess == true)402 str=str+'<i class="fa fa-pencil text-primary edit" onclick="updateTheTest('+testID+',\''+testName+'\');"></i>';403 }404 str=str+'</td>';405 str=str+'</tr>';406 $("#tests-table-body").append(str);407 }408 $('.tests-table-loader').hide();409 $("#dtable").DataTable();410// $("#dtable").DataTable( {411// "scrollY": '90vh',412// "scrollCollapse": true,413// "paging": true,414// "scrollX": false,415// "ordering": true,416// "info": true,417// "searching": true,418// "destroy": true419// } );420 }else{421 str += '<tr><td colspan="10"><div class="text-center"> No record found </div></td></tr>';422 $('#tests-table-body').append(str);423 $('.tests-table-loader').hide();424 }425 },426 error : function(itr) {427 alert("Error while processing the request....!!");428 }429 });430 $('#testFilterModal').modal('hide');431}432function testDetails(ths){433 console.log($(ths).attr('value'));434 var testID = $(ths).attr('value');435 window.location.replace("testDetails?testID="+testID); ...

Full Screen

Full Screen

project.js

Source:project.js Github

copy

Full Screen

1/*2 * StoryQuest 23 *4 * Copyright (c) 2014 Questor GmbH5 *6 * Permission is hereby granted, free of charge, to any person obtaining7 * a copy of this software and associated documentation files (the8 * "Software"), to deal in the Software without restriction, including9 * without limitation the rights to use, copy, modify, merge, publish,10 * distribute, sublicense, and/or sell copies of the Software, and to11 * permit persons to whom the Software is furnished to do so, subject to12 * the following conditions:13 *14 * The above copyright notice and this permission notice shall be15 * included in all copies or substantial portions of the Software.16 *17 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,18 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF19 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND20 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE21 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION22 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION23 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.24 */25var config = require(process.env.CONFIGFILE || "../../config.json");26var fs = require("fs");27var path = require("path");28var ncp = require('ncp').ncp;29var nodetypes = require("../logic/nodetypes.js");30exports = module.exports = Project;31function Project() {32 this.id = "project_" + Utils.uuid();33 this.deleted = false;34 this.nodetypes = [];35 this.testKey = Utils.uuid();36 this.apiKey = Utils.uuid();37 this.created = new Date();38 this.changed = new Date();39 this.status = "new";40 this.coverimage = "";41 this.betaActive = false;42 this.ratings = [];43 this.comments = [];44}45Project.prototype.id = null;46Project.type = "project";47Project.deleted = null;48Project.prototype.name = null;49Project.prototype.nodetypes = null;50Project.prototype.testKey = null;51Project.prototype.apiKey = null;52Project.created = null;53Project.changed = null;54Project.description = null;55Project.author = null;56Project.tags = null;57Project.coverimage = null;58Project.betaActive = true;59Project.status = null;60Project.price = undefined;61Project.currency = "EUR";62Project.ratings = null;63Project.comments = null;64Project.prototype.updateData = function(updatedProject, done) {65 if (updatedProject.name) this.name = updatedProject.name;66 if (updatedProject.nodetypes) this.nodetypes = updatedProject.nodetypes;67 if (updatedProject.testKey) this.testKey = updatedProject.testKey;68 if (updatedProject.apiKey) this.apiKey = updatedProject.apiKey;69 this.changed = new Date();70 if (updatedProject.description) this.description = updatedProject.description;71 if (updatedProject.author) this.author = updatedProject.author;72 if (updatedProject.tags) this.tags = updatedProject.tags;73 if (updatedProject.coverimage) this.coverimage = updatedProject.coverimage;74 if (updatedProject.betaActive) this.betaActive = true; else this.betaActive = false;75 if (updatedProject.status) this.status = updatedProject.status;76 if (updatedProject.price) this.price = updatedProject.price;77 if (updatedProject.currency) this.currency = updatedProject.currency;78 if (updatedProject.ratings) this.ratings = updatedProject.ratings;79 if (updatedProject.comments) this.comments = updatedProject.comments;80 Database.save(this.id, this._rev, this, done);81};82Project.prototype.save = function(done) {83 Database.save(this.id, this._rev, Project.toJSON(this), function (err, res) {84 if (err)85 done(err);86 else87 done(null);88 });89};90// FIXME: this is supposed to create needed database views but get never called91Project.databaseInit = function() {92 Database.save('_design/project', {93 byProjectId: {94 map: function (doc) {95 if (doc._id && doc.deleted==false) emit(doc._id, doc);96 }97 },98 byTestKey: {99 map: function (doc) {100 if (doc.testKey && doc.deleted==false) emit(doc.testKey, doc);101 }102 },103 byApiKey: {104 map: function (doc) {105 if (doc.apiKey && doc.deleted==false) emit(doc.apiKey, doc);106 }107 },108 byStatus: {109 map: function (doc) {110 if (doc.status && doc.deleted==false) emit(doc.status, doc);111 }112 }113 });114};115Project.exists = function(projectId, done) {116 Project.getByProjectId(projectId, function(err, project) {117 if (project!=null)118 done(true);119 else120 done(false);121 })122};123Project.getByProjectId = function(projectId, done) {124 Database.view('project/byProjectId', { key: projectId }, function (err, doc) {125 if (err || !doc || doc.length!=1)126 done(err, null);127 else128 done(err, Project.fromJSON(doc[0].value));129 });130};131Project.getByTestKey = function(testKey, done) {132 Database.view('project/byTestKey', { key: testKey }, function (err, doc) {133 if (err || !doc || doc.length!=1)134 done(err, null);135 else136 done(err, Project.fromJSON(doc[0].value));137 });138};139Project.getByApiKey = function(apiKey, done) {140 Database.view('project/byApiKey', { key: apiKey }, function (err, doc) {141 if (err || !doc || doc.length!=1)142 done(err, null);143 else144 done(err, Project.fromJSON(doc[0].value));145 });146};147Project.getByStatus = function(status, done) {148 Database.view('project/byStatus', { key: status }, function (err, doc) {149 if (err || !doc)150 done(err, null);151 else {152 var result = [];153 for (var i=0; i<doc.length; i++)154 result.push(Project.fromJSON(doc[i].value));155 done(err, result);156 }157 });158};159Project.fromJSON = function(dbDoc) {160 var project = new Project();161 project.id = dbDoc._id;162 project._rev = dbDoc._rev;163 project.name = dbDoc.name;164 project.type = dbDoc.type;165 project.testKey = dbDoc.testKey;166 project.apiKey = dbDoc.apiKey;167 project.nodetypes = dbDoc.nodetypes;168 project.deleted = dbDoc.deleted;169 project.created = dbDoc.created;170 project.changed = dbDoc.changed;171 project.description = dbDoc.description;172 project.author = dbDoc.author;173 project.tags = dbDoc.tags;174 project.coverimage = dbDoc.coverimage;175 project.betaActive = dbDoc.betaActive;176 project.status = dbDoc.status;177 project.price = dbDoc.price;178 project.currency = dbDoc.currency;179 project.ratings = dbDoc.ratings;180 project.comments = dbDoc.comments;181 return project;182};183Project.toJSON = function(project) {184 var dbDoc = {};185 if (project.id)186 dbDoc._id = project.id;187 if (project._rev)188 dbDoc._rev = project._rev;189 dbDoc.name = project.name;190 dbDoc.type = project.type;191 dbDoc.testKey = project.testKey;192 dbDoc.apiKey = project.apiKey;193 dbDoc.nodetypes = project.nodetypes;194 dbDoc.deleted = project.deleted;195 dbDoc.created = project.created;196 dbDoc.changed = project.changed;197 dbDoc.description = project.description;198 dbDoc.author = project.author;199 dbDoc.tags = project.tags;200 dbDoc.coverimage = project.coverimage;201 dbDoc.betaActive = project.betaActive;202 dbDoc.status = project.status;203 dbDoc.price = project.price;204 dbDoc.currency = project.currency;205 dbDoc.ratings = project.ratings;206 dbDoc.comments = project.comments;207 return dbDoc;208};209Project.createInDatabase = function(name, description, tags, context, author, done) {210 var newProject = new Project();211 newProject.name = name;212 newProject.nodetypes = nodetypes.getAvailableNodeTypes(context);213 newProject.description = description;214 newProject.tags = tags;215 newProject.ratings = [];216 newProject.comments = [];217 newProject.status = "new";218 newProject.author = author;219 Database.save(Project.toJSON(newProject), function (err, res) {220 if (err) {221 logger.error("Error storing new project to database: " + JSON.stringify(err) + " " + JSON.stringify(newProject));222 done(err, null);223 } else {224 logger.info("Created project " + newProject.id);225 done(null, res);226 }227 });228};229Project.delete = function(projectId, done) {230 Project.getByProjectId(projectId, function(err, project) {231 if (err)232 done(err);233 else {234 Database.remove(project.id, project._rev, function(err, res) {235 done(err);236 })237 }238 })239};240Project.createProjectDirectory = function(project, context) {241 // FIXME: up the chain, make sure project.id does not contain .,/,\242 var projectDir = Utils.getProjectDir(project.id);243 fs.mkdirSync(projectDir);244 fs.mkdirSync(path.join(projectDir, "stationconfig"));245 fs.mkdirSync(path.join(projectDir, "images"));246 if (context) {247 var contextTemplatePath = path.join(__dirname, "..", "..", "templates-context", context);248 if (fs.existsSync(contextTemplatePath)) {249 ncp(contextTemplatePath, projectDir, function (err) {250 if (err) {251 logger.error("Error copying context template " + context);252 } else {253 logger.info("Copied context template " + context + " for project " + project.id);254 }255 });256 }257 }...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1var byTestKey = require('stryker-parent').byTestKey;2var test = require('tape');3test('test', function (t) {4 t.plan(1);5 t.equal(byTestKey('test'), 'test');6});7var byTestKey = require('stryker-test').byTestKey;8module.exports = {9};10var byTestKey = function (key) {11 return key;12};13module.exports = {14};

Full Screen

Using AI Code Generation

copy

Full Screen

1var byTestKey = require('stryker-parent').byTestKey;2var testKey = byTestKey('test.js');3console.log(testKey);4var byTestKey = require('stryker-parent').byTestKey;5var testKey = byTestKey('test.js');6console.log(testKey);7var byTestKey = require('stryker-parent').byTestKey;8var testKey = byTestKey('test.js');9console.log(testKey);10var byTestKey = require('stryker-parent').byTestKey;11var testKey = byTestKey('test.js');12console.log(testKey);13var byTestKey = require('stryker-parent').byTestKey;14var testKey = byTestKey('test.js');15console.log(testKey);16var byTestKey = require('stryker-parent').byTestKey;17var testKey = byTestKey('test.js');18console.log(testKey);19var byTestKey = require('stryker-parent').byTestKey;20var testKey = byTestKey('test.js');21console.log(testKey);22var byTestKey = require('stryker-parent').byTestKey;23var testKey = byTestKey('test.js');24console.log(testKey);25var byTestKey = require('stryker-parent').byTestKey;26var testKey = byTestKey('test.js');27console.log(testKey);

Full Screen

Using AI Code Generation

copy

Full Screen

1const parent = require('stryker-parent');2const child = require('stryker-child');3const result = parent.byTestKey(child.testKey());4console.log(result);5const child = require('stryker-child');6module.exports = {7 byTestKey: function(testKey) {8 return child.byTestKey(testKey);9 }10};11module.exports = {12 byTestKey: function(testKey) {13 return testKey;14 },15 testKey: function() {16 return Math.random();17 }18};19module.exports = function(config) {20 config.set({21 });22};

Full Screen

Using AI Code Generation

copy

Full Screen

1var byTestKey = require('stryker-parent').byTestKey;2var testKey = 'testKey';3var value = byTestKey(testKey);4console.log('value: ' + value);5{6 "dependencies": {7 }8}

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run stryker-parent automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful