ScenarioModel.js 12.8 KB
Newer Older
Q
q4speed 已提交
1 2 3 4 5 6 7 8 9 10 11
import {
  Element,
  HTTPSamplerProxy,
  HashTree,
  TestElement,
  TestPlan,
  ThreadGroup,
  HeaderManager,
  HTTPSamplerArguments,
  ResponseCodeAssertion,
  ResponseDataAssertion,
Q
NaN  
q4speed 已提交
12
  ResponseHeadersAssertion,
Q
q4speed 已提交
13
  BackendListener, RegexExtractor, JSONPostProcessor, XPath2Extractor, Arguments
Q
q4speed 已提交
14 15
} from "./JMX";

Q
q4speed 已提交
16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
export const uuid = function () {
  let d = new Date().getTime()
  let d2 = (performance && performance.now && (performance.now() * 1000)) || 0;
  return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
    let r = Math.random() * 16;
    if (d > 0) {
      r = (d + r) % 16 | 0;
      d = Math.floor(d / 16);
    } else {
      r = (d2 + r) % 16 | 0;
      d2 = Math.floor(d2 / 16);
    }
    return (c === 'x' ? r : (r & 0x3 | 0x8)).toString(16);
  });
}
Q
q4speed 已提交
31 32

export const BODY_TYPE = {
Q
q4speed 已提交
33 34 35
  KV: "KeyValue",
  FORM_DATA: "Form Data",
  RAW: "Raw"
Q
q4speed 已提交
36 37 38
}

export const ASSERTION_TYPE = {
Q
q4speed 已提交
39 40 41
  TEXT: "Text",
  REGEX: "Regex",
  RESPONSE_TIME: "Response Time"
Q
q4speed 已提交
42 43
}

Q
q4speed 已提交
44 45 46 47 48 49
export const ASSERTION_REGEX_SUBJECT = {
  RESPONSE_CODE: "Response Code",
  RESPONSE_HEADERS: "Response Headers",
  RESPONSE_DATA: "Response Data"
}

Q
q4speed 已提交
50 51 52 53 54 55
export const EXTRACT_TYPE = {
  REGEX: "Regex",
  JSON_PATH: "JSONPath",
  XPATH: "XPath"
}

Q
q4speed 已提交
56
export class BaseConfig {
Q
q4speed 已提交
57 58 59 60 61 62 63 64 65 66 67

  set(options) {
    options = this.initOptions(options)

    for (let name in options) {
      if (options.hasOwnProperty(name)) {
        if (!(this[name] instanceof Array)) {
          this[name] = options[name];
        }
      }
    }
Q
q4speed 已提交
68 69
  }

Q
q4speed 已提交
70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85
  sets(types, options) {
    options = this.initOptions(options)
    if (types) {
      for (let name in types) {
        if (types.hasOwnProperty(name) && options.hasOwnProperty(name)) {
          options[name].forEach((o) => {
            this[name].push(new types[name](o));
          })
        }
      }
    }
  }

  initOptions(options) {
    return options || {};
  }
Q
q4speed 已提交
86 87 88 89

  isValid() {
    return true;
  }
Q
q4speed 已提交
90 91 92 93 94
}

export class Test extends BaseConfig {
  constructor(options) {
    super();
Q
q4speed 已提交
95
    this.version = '1.0.0';
Q
q4speed 已提交
96
    this.id = uuid();
Q
q4speed 已提交
97 98
    this.name = undefined;
    this.projectId = undefined;
Q
q4speed 已提交
99 100
    this.scenarioDefinition = [];

Q
q4speed 已提交
101 102
    this.set(options);
    this.sets({scenarioDefinition: Scenario}, options);
Q
q4speed 已提交
103 104
  }

Q
q4speed 已提交
105
  initOptions(options) {
Q
q4speed 已提交
106 107 108 109
    options = options || {};
    options.scenarioDefinition = options.scenarioDefinition || [new Scenario()];
    return options;
  }
Q
q4speed 已提交
110 111 112 113 114 115 116

  toJMX() {
    return {
      name: this.name + '.jmx',
      xml: new JMXGenerator(this).toXML()
    };
  }
Q
q4speed 已提交
117 118
}

Q
q4speed 已提交
119
export class Scenario extends BaseConfig {
Q
q4speed 已提交
120
  constructor(options) {
Q
q4speed 已提交
121
    super();
Q
q4speed 已提交
122 123
    this.name = undefined;
    this.url = undefined;
Q
q4speed 已提交
124
    this.variables = [];
Q
q4speed 已提交
125 126 127
    this.headers = [];
    this.requests = [];

Q
q4speed 已提交
128
    this.set(options);
Q
q4speed 已提交
129
    this.sets({variables: KeyValue, headers: KeyValue, requests: Request}, options);
Q
q4speed 已提交
130 131
  }

Q
q4speed 已提交
132
  initOptions(options) {
Q
q4speed 已提交
133 134 135
    options = options || {};
    options.requests = options.requests || [new Request()];
    return options;
Q
q4speed 已提交
136 137 138
  }
}

Q
q4speed 已提交
139
export class Request extends BaseConfig {
Q
q4speed 已提交
140
  constructor(options) {
Q
q4speed 已提交
141
    super();
Q
q4speed 已提交
142 143 144
    this.name = undefined;
    this.url = undefined;
    this.method = undefined;
Q
q4speed 已提交
145 146
    this.parameters = [];
    this.headers = [];
Q
q4speed 已提交
147 148 149
    this.body = undefined;
    this.assertions = undefined;
    this.extract = undefined;
Q
q4speed 已提交
150

Q
q4speed 已提交
151 152
    this.set(options);
    this.sets({parameters: KeyValue, headers: KeyValue}, options);
Q
q4speed 已提交
153 154
  }

Q
q4speed 已提交
155
  initOptions(options) {
Q
q4speed 已提交
156
    options = options || {};
Q
q4speed 已提交
157
    options.method = options.method || "GET";
Q
q4speed 已提交
158 159
    options.body = new Body(options.body);
    options.assertions = new Assertions(options.assertions);
Q
q4speed 已提交
160
    options.extract = new Extract(options.extract);
Q
q4speed 已提交
161
    return options;
Q
q4speed 已提交
162
  }
Q
q4speed 已提交
163 164 165 166

  isValid() {
    return !!this.url && !!this.method
  }
Q
q4speed 已提交
167 168
}

Q
q4speed 已提交
169
export class Body extends BaseConfig {
Q
q4speed 已提交
170
  constructor(options) {
Q
q4speed 已提交
171
    super();
Q
q4speed 已提交
172 173
    this.type = undefined;
    this.raw = undefined;
Q
q4speed 已提交
174 175
    this.kvs = [];

Q
q4speed 已提交
176 177
    this.set(options);
    this.sets({kvs: KeyValue}, options);
Q
q4speed 已提交
178 179
  }

Q
q4speed 已提交
180 181 182 183 184 185 186 187 188 189
  isValid() {
    if (this.isKV()) {
      return this.kvs.some(kv => {
        return kv.isValid();
      })
    } else {
      return !!this.raw;
    }
  }

Q
q4speed 已提交
190 191 192 193 194
  isKV() {
    return this.type === BODY_TYPE.KV;
  }
}

Q
q4speed 已提交
195
export class KeyValue extends BaseConfig {
Q
q4speed 已提交
196 197 198 199 200 201 202 203 204 205 206
  constructor() {
    let options, key, value;
    if (arguments.length === 1) {
      options = arguments[0];
    }

    if (arguments.length === 2) {
      key = arguments[0];
      value = arguments[1];
    }

Q
q4speed 已提交
207
    super();
Q
q4speed 已提交
208 209
    this.name = key;
    this.value = value;
Q
q4speed 已提交
210

Q
q4speed 已提交
211
    this.set(options);
Q
q4speed 已提交
212
  }
Q
q4speed 已提交
213 214 215 216

  isValid() {
    return !!this.name || !!this.value;
  }
Q
q4speed 已提交
217 218
}

Q
q4speed 已提交
219
export class Assertions extends BaseConfig {
Q
q4speed 已提交
220
  constructor(options) {
Q
q4speed 已提交
221
    super();
Q
q4speed 已提交
222 223
    this.text = [];
    this.regex = [];
Q
q4speed 已提交
224
    this.duration = undefined;
Q
q4speed 已提交
225

Q
q4speed 已提交
226
    this.set(options);
Q
q4speed 已提交
227
    this.sets({text: Text, regex: Regex}, options);
Q
q4speed 已提交
228 229
  }

Q
q4speed 已提交
230
  initOptions(options) {
Q
q4speed 已提交
231
    options = options || {};
Q
q4speed 已提交
232
    options.duration = new ResponseTime(options.duration);
Q
q4speed 已提交
233
    return options;
Q
q4speed 已提交
234 235 236
  }
}

Q
q4speed 已提交
237
export class AssertionType extends BaseConfig {
Q
q4speed 已提交
238
  constructor(type) {
Q
q4speed 已提交
239
    super();
Q
q4speed 已提交
240 241 242 243 244 245 246
    this.type = type;
  }
}

export class Text extends AssertionType {
  constructor(options) {
    super(ASSERTION_TYPE.TEXT);
Q
q4speed 已提交
247 248 249
    this.subject = undefined;
    this.condition = undefined;
    this.value = undefined;
Q
q4speed 已提交
250

Q
q4speed 已提交
251
    this.set(options);
Q
q4speed 已提交
252 253 254 255 256 257
  }
}

export class Regex extends AssertionType {
  constructor(options) {
    super(ASSERTION_TYPE.REGEX);
Q
q4speed 已提交
258 259 260
    this.subject = undefined;
    this.expression = undefined;
    this.description = undefined;
Q
q4speed 已提交
261

Q
q4speed 已提交
262
    this.set(options);
Q
q4speed 已提交
263
  }
Q
q4speed 已提交
264 265 266 267

  isValid() {
    return !!this.subject && !!this.expression;
  }
Q
q4speed 已提交
268 269 270 271 272
}

export class ResponseTime extends AssertionType {
  constructor(options) {
    super(ASSERTION_TYPE.RESPONSE_TIME);
Q
q4speed 已提交
273
    this.value = undefined;
Q
q4speed 已提交
274

Q
q4speed 已提交
275
    this.set(options);
Q
q4speed 已提交
276
  }
Q
q4speed 已提交
277 278 279 280

  isValid() {
    return !!this.value;
  }
Q
q4speed 已提交
281 282
}

Q
q4speed 已提交
283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309
export class Extract extends BaseConfig {
  constructor(options) {
    super();
    this.regex = [];
    this.json = [];
    this.xpath = [];

    this.set(options);
    let types = {
      json: ExtractJSONPath,
      xpath: ExtractXPath,
      regex: ExtractRegex
    }
    this.sets(types, options);
  }
}

export class ExtractType extends BaseConfig {
  constructor(type) {
    super();
    this.type = type;
  }
}

export class ExtractCommon extends ExtractType {
  constructor(type, options) {
    super(type);
Q
q4speed 已提交
310
    this.variable = undefined;
Q
q4speed 已提交
311
    this.value = ""; // ${variable}
Q
q4speed 已提交
312 313
    this.expression = undefined;
    this.description = undefined;
Q
q4speed 已提交
314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340

    this.set(options);
  }

  isValid() {
    return !!this.variable && !!this.expression;
  }
}

export class ExtractRegex extends ExtractCommon {
  constructor(options) {
    super(EXTRACT_TYPE.REGEX, options);
  }
}

export class ExtractJSONPath extends ExtractCommon {
  constructor(options) {
    super(EXTRACT_TYPE.JSON_PATH, options);
  }
}

export class ExtractXPath extends ExtractCommon {
  constructor(options) {
    super(EXTRACT_TYPE.XPATH, options);
  }
}

Q
NaN  
q4speed 已提交
341
/** ------------------------------------------------------------------------ **/
Q
q4speed 已提交
342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384
const JMX_ASSERTION_CONDITION = {
  MATCH: 1,
  CONTAINS: 1 << 1,
  NOT: 1 << 2,
  EQUALS: 1 << 3,
  SUBSTRING: 1 << 4,
  OR: 1 << 5
}

class JMXRequest {
  constructor(request) {
    if (request && request instanceof Request && request.url) {
      let url = new URL(request.url);
      this.method = request.method;
      this.hostname = url.hostname;
      this.pathname = url.pathname;
      this.port = url.port;
      this.protocol = url.protocol.split(":")[0];
      if (this.method.toUpperCase() !== "GET") {
        this.pathname += url.search.replace('&', '&amp;');
      }
    }
  }
}

class JMeterTestPlan extends Element {
  constructor() {
    super('jmeterTestPlan', {
      version: "1.2", properties: "5.0", jmeter: "5.2.1"
    });

    this.add(new HashTree());
  }

  put(te) {
    if (te instanceof TestElement) {
      this.elements[0].add(te);
    }
  }
}

class JMXGenerator {
  constructor(test) {
385
    if (!test || !test.id || !(test instanceof Test)) return undefined;
Q
q4speed 已提交
386 387

    let testPlan = new TestPlan(test.name);
388 389 390 391 392 393 394 395 396
    this.addScenarios(testPlan, test.scenarioDefinition);

    this.jmeterTestPlan = new JMeterTestPlan();
    this.jmeterTestPlan.put(testPlan);
  }

  addScenarios(testPlan, scenarios) {
    scenarios.forEach(scenario => {
      let threadGroup = new ThreadGroup(scenario.name || "");
Q
q4speed 已提交
397

Q
q4speed 已提交
398 399 400 401
      this.addScenarioVariables(threadGroup, scenario);

      this.addScenarioHeaders(threadGroup, scenario);

Q
q4speed 已提交
402
      scenario.requests.forEach(request => {
Q
q4speed 已提交
403 404
        if (!request.isValid()) return;

405
        let httpSamplerProxy = new HTTPSamplerProxy(request.name || "", new JMXRequest(request));
Q
q4speed 已提交
406 407 408 409 410 411 412 413 414 415 416

        this.addRequestHeader(httpSamplerProxy, request);

        if (request.method.toUpperCase() === 'GET') {
          this.addRequestArguments(httpSamplerProxy, request);
        } else {
          this.addRequestBody(httpSamplerProxy, request);
        }

        this.addRequestAssertion(httpSamplerProxy, request);

Q
q4speed 已提交
417 418
        this.addRequestExtractor(httpSamplerProxy, request);

Q
q4speed 已提交
419 420 421 422 423
        threadGroup.put(httpSamplerProxy);
      })

      testPlan.put(threadGroup);
    })
424
  }
Q
q4speed 已提交
425

Q
q4speed 已提交
426
  addScenarioVariables(threadGroup, scenario) {
Q
q4speed 已提交
427
    let args = this.replaceKV(scenario.variables);
Q
q4speed 已提交
428 429 430 431 432 433 434
    if (args.length > 0) {
      let name = scenario.name + " Variables"
      threadGroup.put(new Arguments(name, args));
    }
  }

  addScenarioHeaders(threadGroup, scenario) {
Q
q4speed 已提交
435
    let headers = this.replaceKV(scenario.headers);
Q
q4speed 已提交
436 437 438 439 440 441
    if (headers.length > 0) {
      let name = scenario.name + " Headers"
      threadGroup.put(new HeaderManager(name, headers));
    }
  }

Q
q4speed 已提交
442 443
  addRequestHeader(httpSamplerProxy, request) {
    let name = request.name + " Headers";
Q
q4speed 已提交
444
    let headers = this.replaceKV(request.headers);
Q
q4speed 已提交
445
    if (headers.length > 0) {
Q
q4speed 已提交
446
      httpSamplerProxy.put(new HeaderManager(name, headers));
Q
q4speed 已提交
447
    }
Q
q4speed 已提交
448 449 450
  }

  addRequestArguments(httpSamplerProxy, request) {
Q
q4speed 已提交
451
    let args = this.replaceKV(request.parameters);
Q
q4speed 已提交
452
    if (args.length > 0) {
Q
q4speed 已提交
453
      httpSamplerProxy.add(new HTTPSamplerArguments(args));
Q
q4speed 已提交
454
    }
Q
q4speed 已提交
455 456 457 458 459 460 461
  }

  addRequestBody(httpSamplerProxy, request) {
    let body = [];
    if (request.body.isKV()) {
      body = request.body.kvs.filter(this.filter);
    } else {
Q
q4speed 已提交
462
      httpSamplerProxy.boolProp('HTTPSampler.postBodyRaw', true);
Q
q4speed 已提交
463 464 465
      body.push({name: '', value: request.body.raw});
    }

Q
q4speed 已提交
466
    httpSamplerProxy.add(new HTTPSamplerArguments(body));
Q
q4speed 已提交
467 468 469 470 471 472
  }

  addRequestAssertion(httpSamplerProxy, request) {
    let assertions = request.assertions;
    if (assertions.regex.length > 0) {
      assertions.regex.filter(this.filter).forEach(regex => {
Q
q4speed 已提交
473
        httpSamplerProxy.put(this.getAssertion(regex));
Q
q4speed 已提交
474 475 476 477
      })
    }

    if (assertions.duration.isValid()) {
Q
q4speed 已提交
478
      httpSamplerProxy.put(assertions.duration.type, assertions.duration.value);
Q
q4speed 已提交
479 480 481 482 483
    }
  }

  getAssertion(regex) {
    let name = regex.description;
Q
q4speed 已提交
484
    let type = JMX_ASSERTION_CONDITION.CONTAINS; // 固定用Match,自己写正则
Q
q4speed 已提交
485
    let value = this.replace(regex.expression);
Q
q4speed 已提交
486 487 488 489 490 491 492 493 494 495
    switch (regex.subject) {
      case ASSERTION_REGEX_SUBJECT.RESPONSE_CODE:
        return new ResponseCodeAssertion(name, type, value);
      case ASSERTION_REGEX_SUBJECT.RESPONSE_DATA:
        return new ResponseDataAssertion(name, type, value);
      case ASSERTION_REGEX_SUBJECT.RESPONSE_HEADERS:
        return new ResponseHeadersAssertion(name, type, value);
    }
  }

Q
q4speed 已提交
496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537
  addRequestExtractor(httpSamplerProxy, request) {
    let extract = request.extract;
    if (extract.regex.length > 0) {
      extract.regex.filter(this.filter).forEach(regex => {
        httpSamplerProxy.put(this.getExtractor(regex));
      })
    }

    if (extract.json.length > 0) {
      extract.json.filter(this.filter).forEach(json => {
        httpSamplerProxy.put(this.getExtractor(json));
      })
    }

    if (extract.xpath.length > 0) {
      extract.xpath.filter(this.filter).forEach(xpath => {
        httpSamplerProxy.put(this.getExtractor(xpath));
      })
    }
  }

  getExtractor(extractCommon) {
    let props = {
      name: extractCommon.variable,
      expression: extractCommon.expression,
    }
    let testName = props.name
    switch (extractCommon.type) {
      case EXTRACT_TYPE.REGEX:
        testName += " RegexExtractor";
        props.headers = "false"; // 对应jMeter body
        props.template = "$1$";
        return new RegexExtractor(testName, props);
      case EXTRACT_TYPE.JSON_PATH:
        testName += " JSONExtractor";
        return new JSONPostProcessor(testName, props);
      case EXTRACT_TYPE.XPATH:
        testName += " XPath2Evaluator";
        return new XPath2Extractor(testName, props);
    }
  }

Q
q4speed 已提交
538 539 540 541
  filter(config) {
    return config.isValid();
  }

Q
q4speed 已提交
542 543 544 545 546 547 548 549 550 551 552 553 554 555
  replace(str) {
    return str.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/'/g, "&apos;").replace(/"/g, "&quot;");
  }

  replaceKV(kvs) {
    let results = [];
    kvs.filter(this.filter).forEach(kv => {
      let name = this.replace(kv.name);
      let value = this.replace(kv.value);
      results.push(new KeyValue(name, value));
    });
    return results;
  }

Q
q4speed 已提交
556 557 558 559 560 561 562 563
  toXML() {
    let xml = '<?xml version="1.0" encoding="UTF-8"?>\n';
    xml += this.jmeterTestPlan.toXML();
    return xml;
  }
}