이 레슨에서 배우는 것
- 요청·대기·반복으로 흐름 만들기
- capture로 토큰·ID를 다음 요청에 넘기기
- CSV 데이터와 JavaScript 프로세서로 확장하기
요청 작성
pizza.ymlyaml
config:
target: http://localhost:3333
phases:
- duration: 60
arrivalRate: 2
defaults:
headers:
Authorization: "token abcdef0123456789" # QuickPizza 데모용 고정 토큰
scenarios:
- name: 피자 추천
flow:
- get:
url: "/"
- think: 1
- post:
url: "/api/pizza"
json: # JSON 본문 (Content-Type 자동 설정)
maxCaloriesPerSlice: 700
mustBeVegetarian: false
capture:
- json: "$.pizza.id" # 응답에서 값 추출
as: pizzaId
- log: "추천받은 피자 ID: {{ pizzaId }}"{{ 변수 }}로 값을 참조합니다. 요청마다 headers, qs(쿼리 문자열), form(폼 본문), body(문자열 본문)를 지정할 수 있습니다.
capture — 상관관계
로그인 응답의 토큰을 저장해 이후 요청에 쓰는 전형적인 흐름입니다. 경로는 예시이므로 실제 API에 맞게 바꾸세요.
yaml
scenarios:
- name: 로그인 후 주문 조회
flow:
- post:
url: "/auth/login"
json:
username: "{{ username }}"
password: "{{ password }}"
capture:
- json: "$.accessToken"
as: token
- get:
url: "/me/orders"
headers:
Authorization: "Bearer {{ token }}"
capture:
- json: "$.orders[0].id"
as: orderId
- get:
url: "/orders/{{ orderId }}"| capture 방식 | 예 |
|---|---|
json | $.data.items[0].id |
regexp | orderId=(\d+) (group로 그룹 지정) |
header | location |
selector + attr | HTML에서 input[name=_csrf]의 value |
💡
capture에 실패하면(값이 없으면) 그 가상 사용자는 기본적으로 중단되어 vusers.failed로 집계됩니다. 로그인이 실패했는데 뒤 요청을 계속 보내 지표를 오염시키는 일을 막아 줍니다.
CSV 데이터 — payload
users.csvtext
username,password
user01,pass-01
user02,pass-02
user03,pass-03yaml
config:
target: https://staging.example.com
payload:
path: "users.csv"
fields: ["username", "password"]
skipHeader: true # 첫 줄(헤더) 건너뛰기
order: sequence # 순서대로 (기본은 random)가상 사용자마다 한 행이 배정되어 {{ username }}, {{ password }}로 쓸 수 있습니다. 비밀번호 같은 비밀 값은 저장소에 커밋하지 말고 CI에서 파일을 생성하거나 환경 변수를 쓰세요.
변수와 환경 값
yaml
config:
target: "{{ $env.TARGET_URL }}" # 환경 변수
variables:
keyword: ["pizza", "pasta", "salad"] # 배열이면 사용자마다 무작위로 하나
scenarios:
- flow:
- get:
url: "/search?q={{ keyword }}&ts={{ $timestamp }}"
headers:
X-Request-Id: "{{ $randomString() }}"환경별 설정은 config.environments에 정의하고 artillery run -e staging test.yml로 고를 수도 있습니다.
yaml
config:
environments:
local:
target: http://localhost:3333
staging:
target: https://staging.example.com
phases:
- duration: 300
arrivalRate: 20반복과 시나리오 가중치
yaml
scenarios:
- name: 둘러보기
weight: 7 # 70%의 사용자
flow:
- loop:
- get:
url: "/products?page={{ $loopCount }}"
- think: 2
count: 3 # 3번 반복
- name: 구매
weight: 3 # 30%
flow:
- post:
url: "/orders"
json: { productId: 101, qty: 1 }JavaScript 프로세서
YAML로 표현하기 어려운 로직(서명 계산, 동적 데이터 생성, 복잡한 검증)은 JavaScript 파일의 함수로 작성해 연결합니다.
processor.jsjavascript
const crypto = require('crypto');
// 요청 전에 HMAC 서명 헤더 추가
function signRequest(requestParams, context, ee, next) {
const body = JSON.stringify(requestParams.json || {});
const ts = Date.now().toString();
const sig = crypto.createHmac('sha256', process.env.API_SECRET || 'dev')
.update(ts + body).digest('hex');
requestParams.headers = { ...requestParams.headers, 'X-Timestamp': ts, 'X-Signature': sig };
return next();
}
// 응답 후 검사, 커스텀 지표 기록
function checkOrder(requestParams, response, context, ee, next) {
if (response.statusCode === 201) {
ee.emit('counter', 'orders.created', 1); // 커스텀 카운터
} else {
ee.emit('counter', 'orders.failed', 1);
}
return next();
}
// 함수 단계: 변수 생성
function makeOrder(context, events, done) {
context.vars.qty = Math.floor(Math.random() * 3) + 1;
return done();
}
module.exports = { signRequest, checkOrder, makeOrder };yaml
config:
target: https://staging.example.com
processor: "./processor.js"
scenarios:
- flow:
- function: makeOrder
- post:
url: "/orders"
json: { productId: 101, qty: "{{ qty }}" }
beforeRequest: signRequest
afterResponse: checkOrder프로세서에서 npm 패키지도 require할 수 있습니다(테스트 폴더에 package.json과 함께 설치).
정리
- 요청은
get/post단계로, 값 전달은capture→{{ 변수 }}로 합니다. - 사용자별 데이터는
payload(CSV), 환경별 설정은environments로 분리합니다. - 복잡한 로직은 JavaScript 프로세서의
beforeRequest·afterResponse·function으로 확장합니다.