Boost Test Automation with NumPy: 5 Essential Array Creation Functions
The article introduces five core NumPy array creation functions—np.array, np.zeros, np.ones, np.arange, and np.linspace—explaining their use cases in interface automation, performance testing, and large‑scale test data generation, and provides concrete code examples and best‑practice tips.
np.array(): One‑click packaging of existing data
In interface automation, test cases are often read from CSV, JSON, or databases and need to be converted into NumPy arrays for matrix operations or bulk assertions.
This basic creation method accepts Python lists, tuples, or nested structures. NumPy requires uniform element types; mixed types are up‑cast (e.g., integers and floats become float) or downgraded to object, which slows computation.
import numpy as np
# Convert a simple status‑code list to an array
status_codes = np.array([200, 200, 404, 500])
print("Status code array:", status_codes)Advanced usage can specify the dtype to save memory, for example when handling user IDs and ages.
# Create a 2×2 matrix of user IDs and ages with explicit int32 dtype
user_data = np.array([[1001, 25], [1002, 30]], dtype=np.int32)
print("User data matrix:
", user_data)
print("Data type:", user_data.dtype)np.zeros(): Placeholder for test environment setup
During performance or concurrency testing, a pre‑allocated zero matrix avoids dynamic resizing overhead when recording response times, error counts, etc.
Provide a shape tuple; the default dtype is float64, but an explicit integer dtype is recommended for counters.
# Initialise an array of length 5 to record error counts for 5 APIs
error_counts = np.zeros(5, dtype=int)
print("Initial error counts:", error_counts)Higher‑level example shows allocating a 3×4 matrix for concurrent thread timing.
# Simulate 3 concurrent threads, each recording 4 interface timings
response_times = np.zeros((3, 4), dtype=np.float32)
print("Timing matrix shape:", response_times.shape)
print("Initial matrix:
", response_times)np.ones(): Quick construction of default parameters
When a test needs a batch of identical default values—e.g., 10 users each starting with 100 points—multiplying a ones array by the desired constant generates the data instantly.
# Generate 10 users with an initial score of 100 points
initial_points = np.ones(10, dtype=int) * 100
print("Initial points:", initial_points)An advanced example creates a 3×3 boolean mask where True indicates a full‑assertion requirement.
# Build a 3×3 mask: 1 means assert, 0 means skip
assert_mask = np.ones((3, 3), dtype=bool)
print("Assertion mask:
", assert_mask)np.arange(): Step‑wise generator for test data
Useful for pagination tests or generating large sequential ID ranges; it behaves like Python's range but returns an array and supports floating‑point steps.
# Generate page IDs 0‑9 for pagination testing
page_ids = np.arange(10)
print("Page ID sequence:", page_ids)Advanced usage creates time offsets for load‑testing, e.g., a 0‑5 second range with 0.5 s steps.
# Simulate sending a request every 0.5 s, 10 timestamps total
time_offsets = np.arange(0, 5, 0.5)
print("Request time offsets (s):", time_offsets)np.linspace(): Precise control of element count
When benchmarking different concurrency levels, linspace generates a fixed number of evenly spaced values within a range, avoiding the off‑by‑one issues of arange with floating steps.
# Generate 5 equally spaced weights between 0 and 1
weights = np.linspace(0, 1, 5)
print("Test weights:", weights)Higher‑level example creates 10 concurrency levels from 10 to 100, confirming the exact count.
# Generate 10 concurrency levels from 10 to 100
concurrency_levels = np.linspace(10, 100, 10, dtype=int)
print("Concurrency gradient:", concurrency_levels)
print("Actual number generated:", len(concurrency_levels))Test‑development tips
Avoid list comprehensions that first build large Python lists and then convert them to arrays; calling NumPy’s built‑in functions such as arange or zeros directly yields cleaner code and leverages C‑level vectorised operations, often improving script execution speed by dozens of times.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
