testzeus-hypermind
Manage Hypermind code blocks for AI-assisted test steps in TestZeus.
Category: integration · Version: 1.0.0 · Requires: testzeus-auth
Triggers: code block, hypermind, reusable code, code snippet, upload code, AI code, code library, code management
Overview
Hypermind code blocks are reusable code snippets that provide AI-assisted functionality in Gherkin test steps. They enable AI to generate context-aware test steps using your custom code logic.
They are not Test Blocks tests. Test Blocks (executor=test_blocks) are a different test type whose steps are Playwright / tz Python — see testzeus-test-blocks.
Quick Reference
# List code blocks
testzeus hypermind-code-blocks list
# Create code block
testzeus hypermind-code-blocks create \
--name "Auth Helper" \
--code-content "async function authenticate(user, pass) { ... }"
# Create from file
testzeus hypermind-code-blocks create \
--name "Utils" \
--code-file ./utils.py
# Update
testzeus hypermind-code-blocks update block_id --code-content "new code"
# Delete
testzeus hypermind-code-blocks delete block_idCode Block Structure
JavaScript Example
// Auth helper function
async function authenticate(username, password) {
const response = await fetch('/api/auth/login', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ username, password })
});
if (!response.ok) {
throw new Error('Authentication failed');
}
return await response.json();
}
// Export for use in tests
module.exports = { authenticate };Python Example
import requests
def authenticate(username: str, password: str) -> dict:
"""Authenticate user and return session token."""
response = requests.post(
'https://api.example.com/auth/login',
json={'username': username, 'password': password}
)
response.raise_for_status()
return response.json()Create Code Block
From Inline Code
testzeus hypermind-code-blocks create \
--name "API Auth Helper" \
--code-content '
async function authenticate(username, password) {
const response = await fetch(\"/api/auth/login\", {
method: \"POST\",
headers: { \"Content-Type\": \"application/json\" },
body: JSON.stringify({ username, password })
});
return response.json();
}
module.exports = { authenticate };
'From File
# Python file
testzeus hypermind-code-blocks create \
--name "Test Helpers" \
--code-file ./tests/helpers.py
# JavaScript file
testzeus hypermind-code-blocks create \
--name "Browser Utils" \
--code-file ./utils/browser.jsWith Metadata
testzeus hypermind-code-blocks create \
--name "Payment Processor" \
--code-content 'async function processPayment(amount, card) { ... }' \
--tags payment \
--tags integrationManage Code Blocks
List Blocks
# List all
testzeus hypermind-code-blocks list
# Filter by name
testzeus hypermind-code-blocks list --filters name~"auth"
# Get details
testzeus hypermind-code-blocks get block_idUpdate Block
# Update code content
testzeus hypermind-code-blocks update block_id \
--code-content 'async function authenticate(username, token) { ... }'
# Update from file
testzeus hypermind-code-blocks update block_id \
--code-file ./updated-helpers.pyDelete Block
testzeus hypermind-code-blocks delete block_idFile Management
Upload Additional Files
# Upload supporting file
testzeus hypermind-code-blocks upload-file block_id ./config.json
# Upload multiple files
testzeus hypermind-code-blocks upload-file block_id ./module1.py
testzeus hypermind-code-blocks upload-file block_id ./module2.pyRemove Files
# Remove specific file
testzeus hypermind-code-blocks remove-file block_id ./old-module.py
# Clear all files
testzeus hypermind-code-blocks delete-all-files block_idCommon Use Cases
Authentication Helpers
// auth-helper.js
async function login(username, password) {
const token = await fetchToken(username, password);
return { token, authenticated: true };
}
async function logout(token) {
await invalidateToken(token);
return { authenticated: false };
}
module.exports = { login, logout };API Utilities
# api-utils.py
import requests
from typing import Dict, Any
def api_get(endpoint: str, headers: Dict) -> Dict[str, Any]:
response = requests.get(f"https://api.example.com{endpoint}", headers=headers)
response.raise_for_status()
return response.json()
def api_post(endpoint: str, data: Dict, headers: Dict) -> Dict[str, Any]:
response = requests.post(f"https://api.example.com{endpoint}", json=data, headers=headers)
response.raise_for_status()
return response.json()Data Generators
// data-generators.js
function generateUser() {
return {
username: `user_${Date.now()}`,
email: `user_${Date.now()}@test.com`,
password: 'Test123!',
profile: {
firstName: 'Test',
lastName: 'User'
}
};
}
function generateProduct() {
return {
name: `Product ${Math.random().toString(36).substr(2, 9)}`,
price: (Math.random() * 100).toFixed(2),
sku: `SKU-${Date.now()}`
};
}
module.exports = { generateUser, generateProduct };Test Fixtures
# fixtures.py
import json
def load_test_data(filename: str) -> dict:
with open(f'test_data/{filename}') as f:
return json.load(f)
def get_fixture(fixture_name: str) -> dict:
fixtures = {
'valid_user': {'username': 'test', 'password': 'test123'},
'admin': {'username': 'admin', 'password': 'admin123', 'role': 'admin'}
}
return fixtures.get(fixture_name, {})SDK Usage
from testzeus_sdk import TestZeusClient
async def main():
async with TestZeusClient() as client:
# Create code block
block = await client.hypermind_code_blocks.create({
"name": "Auth Helpers",
"code_content": """
async function login(username, password) {
// Implementation
}
module.exports = { login };
"""
})
# Upload supporting file
await client.hypermind_code_blocks.upload_file(
block.id,
"./auth-config.json"
)
# List blocks
blocks = await client.hypermind_code_blocks.get_list()
# Update
await client.hypermind_code_blocks.update(
block.id,
{"code_content": "updated code..."}
)Best Practices
1. Single Responsibility
// Good - single function per concern
async function authenticate() { ... }
async function getUserProfile() { ... }
async function updateSettings() { ... }
// Avoid - mixing concerns
async function doEverything() { /* login, profile, settings, cleanup */ }2. Proper Error Handling
// Good
async function apiCall(endpoint) {
try {
const response = await fetch(endpoint);
if (!response.ok) {
throw new Error(`API error: ${response.status}`);
}
return await response.json();
} catch (error) {
console.error('API call failed:', error);
throw error;
}
}3. Document Your Code
def calculate_total(items: list, tax_rate: float = 0.1) -> float:
"""
Calculate total price including tax.
Args:
items: List of item prices
tax_rate: Tax rate as decimal (default 10%)
Returns:
Total including tax
Example:
>>> calculate_total([10, 20, 30], 0.1)
66.0
"""
subtotal = sum(items)
tax = subtotal * tax_rate
return subtotal + tax4. Version Control
Keep your code blocks in version control:
# Store in git
git add ./hypermind-code/
git commit -m "Add auth helpers"Error Handling
Common Errors
| Error | Cause | Solution |
|---|---|---|
Invalid syntax |
Code has errors | Validate syntax |
File too large |
Code exceeds limit | Split into smaller blocks |
Dependency missing |
References undefined | Include all dependencies |
Validation
Always validate code before creating:
# Validate JavaScript
node --check ./code.js
# Validate Python
python -m py_compile ./code.pyComponent Schema
Use CodeBlockPreview component:
{
"component": "CodeBlockPreview",
"props": {
"name": "Auth Helper",
"language": "javascript",
"preview": "async function authenticate(username, password) { ... }",
"fileCount": 0,
"tags": ["auth", "api"]
}
}Related Skills
- testzeus-test-authoring - Using code blocks in tests
- testzeus-test-blocks - Step-based tests; not Hypermind snippets
- testzeus-knowledge-bases - AI context integration