0Pricing
Load Testing & Performance Benchmarking (JMeter & k6) · درس

تخصيص البيانات في k6

طبّق تخصيص البيانات في نصوص k6 لاستخدام مصادر بيانات خارجية كمدخلات للاختبار.

تخصيص البيانات في k6 درس مجاني في Load Testing & Performance Benchmarking (JMeter & k6) على CoddyKit. هذا هو الدرس 2 من أصل 4. يمكنك قراءة الدرس كاملاً أدناه مجاناً — ثم تمرن عليه مباشرة في المتصفح باستخدام محرر أكواد مدمج ومدرس ذكاء اصطناعي متاح 24/7. هذا الدرس جزء من مسار التعلم في Load Testing & Performance Benchmarking (JMeter & k6)، وتقدمك يتزامن عبر الويب وتطبيق CoddyKit. تتضمن دورة Load Testing & Performance Benchmarking (JMeter & k6) 4 دروس في المجموع.

بعض أجزاء هذا الدرس لم تُترجم بعد وتظهر باللغة الإنجليزية.

Dynamic Data in k6 Tests

When performance testing, you rarely want every virtual user (VU) to do exactly the same thing with the exact same data. Real users behave differently!

Data parameterization is the technique of using external data sources to feed dynamic inputs into your test scripts.

Why Parameterize Test Data?

Imagine testing a login page. If all VUs try to log in with "user1" and "pass1", you're not testing unique user scenarios. This can lead to:

  • Unrealistic load patterns
  • Caching issues
  • Errors from duplicate operations

Parameterization helps simulate diverse, realistic user behavior.

SharedArray for Efficient Data

In k6, the SharedArray is your go-to for loading external data efficiently. It's designed to load data once at the start of the test, and then share it across all virtual users (VUs).

  • Load Once: Prevents redundant file reads.
  • Immutable: Data cannot be changed by VUs.
  • Efficient: Reduces memory overhead.

Loading JSON with SharedArray

Let's start by loading a simple JSON array of user credentials. In a real test, you'd use open('./users.json') to read a local file. For this runnable example, we'll embed the JSON data directly.

import { SharedArray } from 'k6/data';
import http from 'k6/http';
import { sleep } from 'k6/execution';

const users = new SharedArray('user_data', function () {
  // In a real test, you'd use open('./users.json')
  // For this runnable example, we'll use inline JSON data:
  const inlineJson = `[
    {"username": "user1", "password": "password1"},
    {"username": "user2", "password": "password2"}
  ]`;
  return JSON.parse(inlineJson);
});

export default function () {
  const user = users[Math.floor(Math.random() * users.length)]; // Pick a random user
  console.log(`VU ${__VU} using user: ${user.username}`);

  // Simulate a request
  http.get('https://test.k6.io');
  sleep(1);
}

Using Parameterized JSON

With the SharedArray loaded, each virtual user (VU) can pick a unique or random entry to use in its requests. This simulates different users logging in or performing actions.

Notice how we pick a user based on __VU % users.length to distribute users evenly. This user's data is then available for your HTTP requests.

import { SharedArray } from 'k6/data';
import http from 'k6/http';
import { sleep } from 'k6/execution';

const users = new SharedArray('user_data', function () {
  const inlineJson = `[
    {"username": "alice", "password": "passA"},
    {"username": "bob", "password": "passB"},
    {"username": "charlie", "password": "passC"}
  ]`;
  return JSON.parse(inlineJson);
});

export default function () {
  const user = users[__VU % users.length]; // Distribute users evenly
  console.log(`VU ${__VU} logging in as: ${user.username}`);

  const payload = JSON.stringify({
    username: user.username,
    password: user.password,
  });

  const params = {
    headers: {
      'Content-Type': 'application/json',
    },
  };

  // Simulate a login request
  http.post('https://test.k6.io/login', payload, params);
  sleep(1);
}

Loading CSV with SharedArray

CSV (Comma Separated Values) files are another common way to store test data. SharedArray can handle these too, but requires a small parsing step.

Imagine a products.csv file:

product_id,product_name,price
101,Laptop,1200
102,Mouse,25
103,Keyboard,75

You'll read this file and parse each line.

Parsing CSV in k6

To parse CSV data, you'll typically read the file line by line, split by comma, and then map it to an object. The k6/data module doesn't have a built-in CSV parser, so you'll do it manually or use a simple helper.

Here's how to load and parse a CSV string, making sure to skip the header row:

import { SharedArray } from 'k6/data';
import http from 'k6/http';
import { sleep } from 'k6/execution';

const products = new SharedArray('product_data', function () {
  // For runnable example, use inline CSV content
  const csvData = `product_id,product_name,price\n101,Laptop,1200\n102,Mouse,25\n103,Keyboard,75`;

  const lines = csvData.split('\n');
  const headers = lines[0].split(','); // Get headers
  const data = [];

  for (let i = 1; i < lines.length; i++) { // Start from second line (skip header)
    const values = lines[i].split(',');
    const row = {};
    for (let j = 0; j < headers.length; j++) {
      row[headers[j]] = values[j];
    }
    data.push(row);
  }
  return data;
});

export default function () {
  const product = products[__VU % products.length]; // Distribute products
  console.log(`VU ${__VU} viewing product: ${product.product_name}`);

  // Simulate viewing a product page
  http.get(`https://test.k6.io/products/${product.product_id}`);
  sleep(1);
}

Using Parameterized CSV

Once your CSV data is loaded and parsed into an array of objects by SharedArray, you can access its properties just like with JSON data. This allows you to construct dynamic URLs, request bodies, or headers.

In the example, each VU accesses a product's product_id and product_name to simulate browsing different product pages, then adds it to a cart.

import { SharedArray } from 'k6/data';
import http from 'k6/http';
import { sleep } from 'k6/execution';

const products = new SharedArray('product_data', function () {
  const csvData = `product_id,product_name,price\n101,Laptop,1200\n102,Mouse,25\n103,Keyboard,75`;

  const lines = csvData.split('\n');
  const headers = lines[0].split(',');
  const data = [];

  for (let i = 1; i < lines.length; i++) {
    const values = lines[i].split(',');
    const row = {};
    for (let j = 0; j < headers.length; j++) {
      row[headers[j]] = values[j];
    }
    data.push(row);
  }
  return data;
});

export default function () {
  const product = products[__VU % products.length]; // Distribute products
  console.log(`VU ${__VU} adding ${product.product_name} to cart`);

  const payload = JSON.stringify({
    productId: product.product_id,
    quantity: 1,
    price: product.price,
  });

  const params = {
    headers: {
      'Content-Type': 'application/json',
    },
  };

  // Simulate adding a product to cart
  http.post('https://test.k6.io/cart/add', payload, params);
  sleep(1);
}

Distributing Data to VUs

How do VUs get their data? You've seen two common patterns:

  • Random: data[Math.floor(Math.random() * data.length)] - Each VU picks a random item. Good for a large pool of interchangeable data.
  • Even Distribution: data[__VU % data.length] - Each VU gets a unique item in a round-robin fashion. Useful when you have fewer data items than VUs and want to ensure each is used.

Choose the method that best simulates your real user behavior.

Check Your Understanding

Which of the following statements about k6's SharedArray for data parameterization are TRUE?

Recap: Dynamic Data in k6

You've learned how to bring your k6 tests to life with dynamic data! We covered:

  • The importance of data parameterization for realistic tests.
  • Using k6's SharedArray to efficiently load and share data.
  • Examples for loading and using both JSON and CSV data.
  • Strategies for distributing data to individual virtual users.

Next, explore how to extract dynamic values from server responses (correlation)!

الأسئلة الشائعة

هل درس «تخصيص البيانات في k6» مجاني؟

نعم — نص درس «تخصيص البيانات في k6» كامل متاح مجاناً هنا على الويب. لتمرينه بشكل تفاعلي (محرر أكواد مدمج ومدرس ذكاء اصطناعي متاح 24/7) وفتح باقي دورة Load Testing & Performance Benchmarking (JMeter & k6)، انتقل إلى CoddyKit PRO. تتضمن دورة Load Testing & Performance Benchmarking (JMeter & k6) 4 دروس في المجموع.

ماذا ستتعلم في «تخصيص البيانات في k6»؟

طبّق تخصيص البيانات في نصوص k6 لاستخدام مصادر بيانات خارجية كمدخلات للاختبار. تتمرن على Load Testing & Performance Benchmarking (JMeter & k6) مع أكواد عملية تشغلها مباشرة في المتصفح، ومدرس ذكاء اصطناعي متاح 24/7 يجيب على أسئلتك أثناء عملك.

هل أحتاج إلى خبرة سابقة لأبدأ Load Testing & Performance Benchmarking (JMeter & k6)؟

لا تُشترط خبرة سابقة. Load Testing & Performance Benchmarking (JMeter & k6) على CoddyKit منظم للمبتدئين حتى المتقدمين، لذا يمكنك البدء من هنا أو من البداية والتقدم بسرعتك الخاصة. هذا هو الدرس 2 من أصل 4.

كم من الوقت يستغرق درس «تخصيص البيانات في k6»؟

معظم دروس CoddyKit تستغرق حوالي 5–10 دقائق. كل منها موجز وتفاعلي، لذا تحرز تقدماً مستمراً وتستأنف من حيث توقفت عبر الويب والتطبيق.

هل يمكنني كتابة وتشغيل أكواد في درس Load Testing & Performance Benchmarking (JMeter & k6) هذا؟

نعم. كل درس في Load Testing & Performance Benchmarking (JMeter & k6) يتضمن محرر أكواد مدمج، لذا تكتب وتشغل أكواداً حقيقية مباشرة في متصفحك وتحصل على تعليقات فورية من الذكاء الاصطناعي — بدون إعداد محلي.

جميع الدروس في هذه الدورة

  1. سيناريوهات المستخدمين الافتراضيين (VUs)
  2. تخصيص البيانات في k6
  3. التنفيذ السحابي باستخدام k6
  4. المقاييس المخصصة والاتجاهات في k6
← العودة إلى Load Testing & Performance Benchmarking (JMeter & k6)