Best JavaScript code snippet using wpt
update_rules.ts
Source:update_rules.ts
1/*2 * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one3 * or more contributor license agreements. Licensed under the Elastic License;4 * you may not use this file except in compliance with the Elastic License.5 */6import expect from '@kbn/expect';7import { DETECTION_ENGINE_RULES_URL } from '../../../../plugins/security_solution/common/constants';8import { FtrProviderContext } from '../../common/ftr_provider_context';9import {10 createSignalsIndex,11 deleteAllAlerts,12 deleteSignalsIndex,13 getSimpleRuleOutput,14 removeServerGeneratedProperties,15 removeServerGeneratedPropertiesIncludingRuleId,16 getSimpleRuleOutputWithoutRuleId,17 getSimpleMlRule,18 getSimpleMlRuleOutput,19 getSimpleRuleUpdate,20 getSimpleMlRuleUpdate,21} from '../../utils';22// eslint-disable-next-line import/no-default-export23export default ({ getService }: FtrProviderContext) => {24 const supertest = getService('supertest');25 const es = getService('es');26 describe('update_rules', () => {27 describe('update rules', () => {28 beforeEach(async () => {29 await createSignalsIndex(supertest);30 });31 afterEach(async () => {32 await deleteSignalsIndex(supertest);33 await deleteAllAlerts(es);34 });35 it('should update a single rule property of name using a rule_id', async () => {36 // create a simple rule37 await supertest38 .post(DETECTION_ENGINE_RULES_URL)39 .set('kbn-xsrf', 'true')40 .send(getSimpleRuleUpdate('rule-1'))41 .expect(200);42 // update a simple rule's name43 const updatedRule = getSimpleRuleUpdate('rule-1');44 updatedRule.rule_id = 'rule-1';45 updatedRule.name = 'some other name';46 delete updatedRule.id;47 const { body } = await supertest48 .put(DETECTION_ENGINE_RULES_URL)49 .set('kbn-xsrf', 'true')50 .send(updatedRule)51 .expect(200);52 const outputRule = getSimpleRuleOutput();53 outputRule.name = 'some other name';54 outputRule.version = 2;55 const bodyToCompare = removeServerGeneratedProperties(body);56 expect(bodyToCompare).to.eql(outputRule);57 });58 it('should update a single rule property of name using a rule_id with a machine learning job', async () => {59 // create a simple rule60 await supertest61 .post(DETECTION_ENGINE_RULES_URL)62 .set('kbn-xsrf', 'true')63 .send(getSimpleMlRule('rule-1'))64 .expect(200);65 // update a simple rule's name66 const updatedRule = getSimpleMlRuleUpdate('rule-1');67 updatedRule.rule_id = 'rule-1';68 updatedRule.name = 'some other name';69 delete updatedRule.id;70 const { body } = await supertest71 .put(DETECTION_ENGINE_RULES_URL)72 .set('kbn-xsrf', 'true')73 .send(updatedRule)74 .expect(200);75 const outputRule = getSimpleMlRuleOutput();76 outputRule.name = 'some other name';77 outputRule.version = 2;78 const bodyToCompare = removeServerGeneratedProperties(body);79 expect(bodyToCompare).to.eql(outputRule);80 });81 it('should update a single rule property of name using an auto-generated rule_id', async () => {82 const rule = getSimpleRuleUpdate('rule-1');83 delete rule.rule_id;84 // create a simple rule85 const { body: createRuleBody } = await supertest86 .post(DETECTION_ENGINE_RULES_URL)87 .set('kbn-xsrf', 'true')88 .send(rule)89 .expect(200);90 // update a simple rule's name91 const updatedRule = getSimpleRuleUpdate('rule-1');92 updatedRule.rule_id = createRuleBody.rule_id;93 updatedRule.name = 'some other name';94 delete updatedRule.id;95 const { body } = await supertest96 .put(DETECTION_ENGINE_RULES_URL)97 .set('kbn-xsrf', 'true')98 .send(updatedRule)99 .expect(200);100 const outputRule = getSimpleRuleOutputWithoutRuleId();101 outputRule.name = 'some other name';102 outputRule.version = 2;103 const bodyToCompare = removeServerGeneratedPropertiesIncludingRuleId(body);104 expect(bodyToCompare).to.eql(outputRule);105 });106 it('should update a single rule property of name using the auto-generated id', async () => {107 // create a simple rule108 const { body: createdBody } = await supertest109 .post(DETECTION_ENGINE_RULES_URL)110 .set('kbn-xsrf', 'true')111 .send(getSimpleRuleUpdate('rule-1'))112 .expect(200);113 // update a simple rule's name114 const updatedRule = getSimpleRuleUpdate('rule-1');115 updatedRule.name = 'some other name';116 updatedRule.id = createdBody.id;117 delete updatedRule.rule_id;118 const { body } = await supertest119 .put(DETECTION_ENGINE_RULES_URL)120 .set('kbn-xsrf', 'true')121 .send(updatedRule)122 .expect(200);123 const outputRule = getSimpleRuleOutput();124 outputRule.name = 'some other name';125 outputRule.version = 2;126 const bodyToCompare = removeServerGeneratedProperties(body);127 expect(bodyToCompare).to.eql(outputRule);128 });129 it('should change the version of a rule when it updates enabled and another property', async () => {130 // create a simple rule131 await supertest132 .post(DETECTION_ENGINE_RULES_URL)133 .set('kbn-xsrf', 'true')134 .send(getSimpleRuleUpdate('rule-1'))135 .expect(200);136 // update a simple rule's enabled to false and another property137 const updatedRule = getSimpleRuleUpdate('rule-1');138 updatedRule.severity = 'low';139 updatedRule.enabled = false;140 const { body } = await supertest141 .put(DETECTION_ENGINE_RULES_URL)142 .set('kbn-xsrf', 'true')143 .send(updatedRule)144 .expect(200);145 const outputRule = getSimpleRuleOutput();146 outputRule.enabled = false;147 outputRule.severity = 'low';148 outputRule.version = 2;149 const bodyToCompare = removeServerGeneratedProperties(body);150 expect(bodyToCompare).to.eql(outputRule);151 });152 it('should change other properties when it does updates and effectively delete them such as timeline_title', async () => {153 // create a simple rule154 await supertest155 .post(DETECTION_ENGINE_RULES_URL)156 .set('kbn-xsrf', 'true')157 .send(getSimpleRuleUpdate('rule-1'))158 .expect(200);159 const ruleUpdate = getSimpleRuleUpdate('rule-1');160 ruleUpdate.timeline_title = 'some title';161 ruleUpdate.timeline_id = 'some id';162 // update a simple rule's timeline_title163 await supertest164 .put(DETECTION_ENGINE_RULES_URL)165 .set('kbn-xsrf', 'true')166 .send(ruleUpdate)167 .expect(200);168 const ruleUpdate2 = getSimpleRuleUpdate('rule-1');169 ruleUpdate2.name = 'some other name';170 // update a simple rule's name171 const { body } = await supertest172 .put(DETECTION_ENGINE_RULES_URL)173 .set('kbn-xsrf', 'true')174 .send(ruleUpdate2)175 .expect(200);176 const outputRule = getSimpleRuleOutput();177 outputRule.name = 'some other name';178 outputRule.version = 3;179 const bodyToCompare = removeServerGeneratedProperties(body);180 expect(bodyToCompare).to.eql(outputRule);181 });182 it('should give a 404 if it is given a fake id', async () => {183 const simpleRule = getSimpleRuleUpdate();184 simpleRule.id = '5096dec6-b6b9-4d8d-8f93-6c2602079d9d';185 delete simpleRule.rule_id;186 const { body } = await supertest187 .put(DETECTION_ENGINE_RULES_URL)188 .set('kbn-xsrf', 'true')189 .send(simpleRule)190 .expect(404);191 expect(body).to.eql({192 status_code: 404,193 message: 'id: "5096dec6-b6b9-4d8d-8f93-6c2602079d9d" not found',194 });195 });196 it('should give a 404 if it is given a fake rule_id', async () => {197 const simpleRule = getSimpleRuleUpdate();198 simpleRule.rule_id = 'fake_id';199 delete simpleRule.id;200 const { body } = await supertest201 .put(DETECTION_ENGINE_RULES_URL)202 .set('kbn-xsrf', 'true')203 .send(simpleRule)204 .expect(404);205 expect(body).to.eql({206 status_code: 404,207 message: 'rule_id: "fake_id" not found',208 });209 });210 });211 });...
rule_builder.ts
Source:rule_builder.ts
1/*2 * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one3 * or more contributor license agreements. Licensed under the Elastic License;4 * you may not use this file except in compliance with the Elastic License.5 */6import { i18n } from '@kbn/i18n';7import { RoleMapping } from '../../../../common/model';8import { FieldRule, FieldRuleValue } from './field_rule';9import { AllRule } from './all_rule';10import { AnyRule } from './any_rule';11import { Rule } from './rule';12import { ExceptAllRule } from './except_all_rule';13import { ExceptAnyRule } from './except_any_rule';14import { RuleBuilderError } from '.';15interface RuleBuilderResult {16 /** The maximum rule depth within the parsed rule set. */17 maxDepth: number;18 /** The parsed rule set. */19 rules: Rule | null;20}21/**22 * Given a set of raw rules, this constructs a class based tree for consumption by the Role Management UI.23 * This also performs validation on the raw rule set, as it is possible to enter raw JSON in the JSONRuleEditor,24 * so we have no guarantees that the rule set is valid ahead of time.25 *26 * @param rawRules the raw rules to translate.27 */28export function generateRulesFromRaw(rawRules: RoleMapping['rules'] = {}): RuleBuilderResult {29 return parseRawRules(rawRules, null, [], 0);30}31function parseRawRules(32 rawRules: RoleMapping['rules'],33 parentRuleType: string | null,34 ruleTrace: string[],35 depth: number36): RuleBuilderResult {37 const entries = Object.entries(rawRules);38 if (!entries.length) {39 return {40 rules: null,41 maxDepth: 0,42 };43 }44 if (entries.length > 1) {45 throw new RuleBuilderError(46 i18n.translate('xpack.security.management.editRoleMapping.ruleBuilder.expectSingleRule', {47 defaultMessage: `Expected a single rule definition, but found {numberOfRules}.`,48 values: { numberOfRules: entries.length },49 }),50 ruleTrace51 );52 }53 const rule = entries[0];54 const [ruleType, ruleDefinition] = rule;55 return createRuleForType(ruleType, ruleDefinition, parentRuleType, ruleTrace, depth + 1);56}57function createRuleForType(58 ruleType: string,59 ruleDefinition: any,60 parentRuleType: string | null,61 ruleTrace: string[] = [],62 depth: number63): RuleBuilderResult {64 const isRuleNegated = parentRuleType === 'except';65 const currentRuleTrace = [...ruleTrace, ruleType];66 switch (ruleType) {67 case 'field': {68 assertIsObject(ruleDefinition, currentRuleTrace);69 const entries = Object.entries(ruleDefinition);70 if (entries.length !== 1) {71 throw new RuleBuilderError(72 i18n.translate(73 'xpack.security.management.editRoleMapping.ruleBuilder.expectedSingleFieldRule',74 {75 defaultMessage: `Expected a single field, but found {count}.`,76 values: { count: entries.length },77 }78 ),79 currentRuleTrace80 );81 }82 const [field, value] = entries[0] as [string, FieldRuleValue];83 const values = Array.isArray(value) ? value : [value];84 values.forEach((fieldValue) => {85 const valueType = typeof fieldValue;86 if (fieldValue !== null && !['string', 'number', 'boolean'].includes(valueType)) {87 throw new RuleBuilderError(88 i18n.translate(89 'xpack.security.management.editRoleMapping.ruleBuilder.invalidFieldValueType',90 {91 defaultMessage: `Invalid value type for field. Expected one of null, string, number, or boolean, but found {valueType} ({value}).`,92 values: { valueType, value: JSON.stringify(value) },93 }94 ),95 currentRuleTrace96 );97 }98 });99 const fieldRule = new FieldRule(field, value);100 return {101 rules: isRuleNegated ? new ExceptAllRule([fieldRule]) : fieldRule,102 maxDepth: depth,103 };104 }105 case 'any': // intentional fall-through to 'all', as validation logic is identical106 case 'all': {107 if (ruleDefinition != null && !Array.isArray(ruleDefinition)) {108 throw new RuleBuilderError(109 i18n.translate(110 'xpack.security.management.editRoleMapping.ruleBuilder.expectedArrayForGroupRule',111 {112 defaultMessage: `Expected an array of rules, but found {type}.`,113 values: { type: typeof ruleDefinition },114 }115 ),116 currentRuleTrace117 );118 }119 const subRulesResults = ((ruleDefinition as any[]) || []).map((definition: any, index) =>120 parseRawRules(definition, ruleType, [...currentRuleTrace, `[${index}]`], depth)121 ) as RuleBuilderResult[];122 const { subRules, maxDepth } = subRulesResults.reduce(123 (acc, result) => {124 return {125 subRules: [...acc.subRules, result.rules!],126 maxDepth: Math.max(acc.maxDepth, result.maxDepth),127 };128 },129 { subRules: [] as Rule[], maxDepth: 0 }130 );131 if (ruleType === 'all') {132 return {133 rules: isRuleNegated ? new ExceptAllRule(subRules) : new AllRule(subRules),134 maxDepth,135 };136 } else {137 return {138 rules: isRuleNegated ? new ExceptAnyRule(subRules) : new AnyRule(subRules),139 maxDepth,140 };141 }142 }143 case 'except': {144 assertIsObject(ruleDefinition, currentRuleTrace);145 if (parentRuleType !== 'all') {146 throw new RuleBuilderError(147 i18n.translate(148 'xpack.security.management.editRoleMapping.ruleBuilder.exceptOnlyInAllRule',149 {150 defaultMessage: `"except" rule can only exist within an "all" rule.`,151 }152 ),153 currentRuleTrace154 );155 }156 // subtracting 1 from depth because we don't currently count the "except" level itself as part of the depth calculation157 // for the purpose of determining if the rule set is "too complex" for the visual rule editor.158 // The "except" rule MUST be nested within an "all" rule type (see validation above), so the depth itself will always be a non-negative number.159 return parseRawRules(ruleDefinition || {}, ruleType, currentRuleTrace, depth - 1);160 }161 default:162 throw new RuleBuilderError(163 i18n.translate('xpack.security.management.editRoleMapping.ruleBuilder.unknownRuleType', {164 defaultMessage: `Unknown rule type: {ruleType}.`,165 values: { ruleType },166 }),167 currentRuleTrace168 );169 }170}171function assertIsObject(ruleDefinition: any, ruleTrace: string[]) {172 let fieldType: string = typeof ruleDefinition;173 if (Array.isArray(ruleDefinition)) {174 fieldType = 'array';175 }176 if (ruleDefinition && fieldType !== 'object') {177 throw new RuleBuilderError(178 i18n.translate('xpack.security.management.editRoleMapping.ruleBuilder.expectedObjectError', {179 defaultMessage: `Expected an object, but found {type}.`,180 values: { type: fieldType },181 }),182 ruleTrace183 );184 }...
Using AI Code Generation
1var wpt = require('webpagetest');2var wpt = new WebPageTest('www.webpagetest.org');3 if (err) return console.error(err);4 console.log(data);5});6var wpt = require('webpagetest');7var wpt = new WebPageTest('www.webpagetest.org');8 if (err) return console.error(err);9 console.log(data);10});11var wpt = require('webpagetest');12var wpt = new WebPageTest('www.webpagetest.org');13 if (err) return console.error(err);14 console.log(data);15});16var wpt = require('webpagetest');17var wpt = new WebPageTest('www.webpagetest.org');18 if (err) return console.error(err);19 console.log(data);20});21var wpt = require('webpagetest');22var wpt = new WebPageTest('www.webpagetest.org');23 if (err) return console.error(err);24 console.log(data);25});26var wpt = require('webpagetest');27var wpt = new WebPageTest('www.webpagetest.org');
Using AI Code Generation
1var wpt = require('webpagetest');2var options = {3};4var client = wpt('www.webpagetest.org', options.key);5 if (err) return console.error(err);6});7client.getTestResults(data.data.testId, function(err, data) {8 if (err) return console.error(err);9});10client.getTestResults(12345, function(err, data) {11 if (err) return console.error(err);12});13client.getTestResults(12345, {breakdown: true}, function(err, data) {14 if (err) return console.error(err);15});16client.getLocations(function(err, data) {17 if (err) return console.error(err);18});19client.getLocations(function(err, data) {20 if (err) return console.error(err);21});22client.getLocations('US', function(err, data) {23 if (err) return console.error(err);24});25client.getTesters(function(err, data) {26 if (err) return console.error(err);27});28client.getTesters('US', function(err, data) {29 if (err) return console.error(err);30});31client.getTesters('US', 'Dulles', function(err, data) {32 if (err) return console.error(err);33});34client.getTesters('US', 'Dulles', 'Chrome', function(err, data) {35 if (err) return console.error(err);36});37client.getTesters('US', 'Dulles', 'Chrome', 'Win7', function(err, data) {38 if (err)
Using AI Code Generation
1var wpt = require('webpagetest');2var wpt = new WebPageTest('www.webpagetest.org');3var options = {4 videoParams: {5 }6};7wpt.runTest(url, options, function(err, data) {8 if (err) return console.error(err);9 console.log('Test Status:', data.statusText);10 console.log('View your test at:', data.data.userUrl);11 wpt.getTestResults(data.data.testId, function(err, data) {12 if (err) return console.error(err);13 console.log('Test Status:', data.statusText);14 console.log('First View:', data.data.average.firstView);15 console.log('Repeat View:', data.data.average.repeatView);16 });17});18var wpt = require('webpagetest');19var wpt = new WebPageTest('www.webpagetest.org');20var options = {21 videoParams: {22 }23};24wpt.runTest(url, options, function(err, data) {25 if (err) return console.error(err);26 console.log('Test Status:', data.statusText);27 console.log('View your test at:', data.data.userUrl);28 wpt.getTestResults(data.data.testId, function(err, data) {29 if (err) return console.error(err);30 console.log('Test Status:', data.statusText);31 console.log('First View:', data.data.average.firstView);32 console.log('Repeat View:', data.data.average.repeatView);33 });34});35var wpt = require('webpagetest');36var wpt = new WebPageTest('www.webpagetest.org');
Using AI Code Generation
1var wptool = require('wptool');2var rule = wptool.rule;3var rules = wptool.rules;4rules.add(r1);5rules.add(r2);6rules.add(r3);7rules.add(r4);8rules.add(r5);9rules.add(r6);10rules.add(r7);11rules.add(r8);12rules.add(r9);13rules.add(r10);14rules.add(r11);
Using AI Code Generation
1var wptools = require('wptools');2var page = wptools.page('Albert Einstein');3page.getInfobox(function(err, info){4 console.log(info);5});6var wptools = require('wptools');7var page = wptools.page('Albert Einstein');8page.getInfobox(function(err, info){9 console.log(info);10});11var wptools = require('wptools');12var page = wptools.page('Albert Einstein');13page.getInfobox(function(err, info){14 console.log(info);15});16var wptools = require('wptools');17var page = wptools.page('Albert Einstein');18page.getInfobox(function(err, info){19 console.log(info);20});21var wptools = require('wptools');22var page = wptools.page('Albert Einstein');23page.getInfobox(function(err, info){24 console.log(info);25});26var wptools = require('wptools');27var page = wptools.page('Albert Einstein');28page.getInfobox(function(err, info){29 console.log(info);30});31var wptools = require('wptools');32var page = wptools.page('Albert Einstein');33page.getInfobox(function(err, info){34 console.log(info);35});
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.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!