### Install Scythe Dependencies
Source: https://github.com/epyklab/scythe/blob/master/docs/GETTING_STARTED.md
Installs the necessary Python dependencies for Scythe from the requirements.txt file. Ensure you have cloned the repository and are in the project directory before running this command.
```bash
pip install -r requirements.txt
```
--------------------------------
### Quick Test for Scythe Installation
Source: https://github.com/epyklab/scythe/blob/master/docs/GETTING_STARTED.md
A quick Python script to test the Scythe installation. It creates a static payload generator and a LoginBruteforceTTP instance to ensure core components are working as expected.
```python
# test_installation.py
from scythe.core.executor import TTPExecutor
from scythe.ttps.web.login_bruteforce import LoginBruteforceTTP
from scythe.payloads.generators import StaticPayloadGenerator
# Create a simple test
payload_generator = StaticPayloadGenerator(["test123"])
login_ttp = LoginBruteforceTTP(
payload_generator=payload_generator,
username="admin",
username_selector="#username",
password_selector="#password",
submit_selector="#submit"
)
print("✅ Installation verified - Scythe is ready to use!")
```
--------------------------------
### Verify Scythe Installation
Source: https://github.com/epyklab/scythe/blob/master/docs/GETTING_STARTED.md
Verifies the Scythe installation by importing the TTPExecutor class and printing a success message. This command confirms that Scythe can be imported and is ready for use.
```python
from scythe.core.executor import TTPExecutor
print('✅ Scythe installed successfully!')
```
--------------------------------
### Run Example Scripts (Bash)
Source: https://github.com/epyklab/scythe/blob/master/docs/VERSION_HEADER_GUIDE.md
Commands to execute the provided Python example scripts for testing version detection and servers. Assumes Python 3 is installed.
```bash
# Start test server
python examples/test_server_with_version.py 8080 1.3.2
# Run example tests (in another terminal)
python examples/version_header_example.py http://localhost:8080
```
--------------------------------
### Scythe API Quickstart with JourneyExecutor
Source: https://github.com/epyklab/scythe/blob/master/docs/GETTING_STARTED.md
Demonstrates how to run Scythe journeys directly against REST APIs using JourneyExecutor in API mode with ApiRequestAction. No browser is required. The executor handles requests via requests.Session.
```python
from scythe.journeys.base import Journey, Step
from scythe.journeys.actions import ApiRequestAction
from scythe.journeys.executor import JourneyExecutor
step = Step(
name="Ping API",
description="GET /api/health should return 200",
actions=[ApiRequestAction(method="GET", url="/api/health", expected_status=200)],
)
journey = Journey(name="API Smoke", description="Simple API health check", steps=[step])
executor = JourneyExecutor(journey=journey, target_url="http://localhost:8080", mode="API")
results = executor.run()
print("Overall:", results.get("overall_success"))
```
--------------------------------
### Test Server Startup (Bash)
Source: https://github.com/epyklab/scythe/blob/master/docs/VERSION_HEADER_GUIDE.md
Starts a test server with a specified version and port. This command is used to set up a controlled environment for testing Scythe's version detection and header functionality. It requires Python to be installed and accessible in the PATH.
```bash
# Start test server with version 1.3.2 on port 8080
python examples/test_server_with_version.py 8080 1.3.2
```
--------------------------------
### Installing WebDriver Manager for ChromeDriver
Source: https://github.com/epyklab/scythe/blob/master/docs/GETTING_STARTED.md
A bash command to install the webdriver-manager Python package. This package helps in automatically managing browser drivers like ChromeDriver, which is often required for browser automation tasks.
```bash
# Install ChromeDriver manually or use webdriver-manager
pip install webdriver-manager
```
--------------------------------
### Run Scythe TTP from Command Line
Source: https://github.com/epyklab/scythe/blob/master/docs/GETTING_STARTED.md
Executes a Python script that contains Scythe TTP configurations. This command initiates the browser automation and TTP execution as defined in the script.
```bash
python my_first_ttp.py
```
--------------------------------
### Sequential TTP Execution with TTPExecutor
Source: https://github.com/epyklab/scythe/blob/master/docs/GETTING_STARTED.md
Shows how to execute multiple TTPs in a sequence against the same target URL. Each TTP is defined and then run using the TTPExecutor, with output indicating the current TTP being executed.
```python
# Run multiple TTPs against same target tps = [
("Login Brute Force", login_ttp),
("SQL Injection", sql_ttp),
("Form Injection", form_sql_ttp)
]
for name, ttp in ttps:
print(f"\n=== Running {name} ===")
executor = TTPExecutor(
ttp=ttp,
target_url="http://example.com"
)
executor.run()
```
--------------------------------
### Create and Run First Scythe TTP
Source: https://github.com/epyklab/scythe/blob/master/docs/GETTING_STARTED.md
Demonstrates creating and running a basic login brute force TTP using Scythe. It sets up a payload generator, configures the TTP with selectors, and executes it against a target URL.
```python
# my_first_ttp.py
from scythe.core.executor import TTPExecutor
from scythe.ttps.web.login_bruteforce import LoginBruteforceTTP
from scythe.payloads.generators import StaticPayloadGenerator
# 1. Create payload generator with common passwords
passwords = StaticPayloadGenerator([
"password",
"123456",
"admin",
"letmein",
"qwerty"
])
# 2. Create the TTP
login_ttp = LoginBruteforceTTP(
payload_generator=passwords,
username="admin", # Username to test
username_selector="#username", # CSS selector for username field
password_selector="#password", # CSS selector for password field
submit_selector="#submit" # CSS selector for submit button
)
# 3. Create and run the executor
executor = TTPExecutor(
ttp=login_ttp,
target_url="http://testphp.vulnweb.com/login.php",
headless=False # Set to True to hide browser
)
# 4. Run the test
executor.run()
```
--------------------------------
### Custom XSS TTP Implementation in Python
Source: https://github.com/epyklab/scythe/blob/master/docs/GETTING_STARTED.md
Provides a Python example of creating a custom TTP class that inherits from Scythe's TTP base class. This custom TTP is designed to test for cross-site scripting (XSS) vulnerabilities.
```python
from scythe.core.ttp import TTP
from selenium.webdriver.common.by import By
class CustomXSSTTP(TTP):
def __init__(self, target_url, input_selector):
super().__init__(
name="XSS Test",
description="Tests for cross-site scripting"
)
self.target_url = target_url
self.input_selector = input_selector
self.payloads = [
"",
"
"
]
def get_payloads(self):
yield from self.payloads
def execute_step(self, driver, payload):
driver.get(self.target_url)
input_field = driver.find_element(By.CSS_SELECTOR, self.input_selector)
input_field.send_keys(payload)
input_field.submit()
def verify_result(self, driver):
return "alert" in driver.page_source.lower()
```
--------------------------------
### Scythe Hybrid Cookie-Based JWT Authentication
Source: https://github.com/epyklab/scythe/blob/master/docs/GETTING_STARTED.md
Illustrates using CookieJWTAuth for applications that authenticate via a JWT stored in a cookie. This example logs in via API, extracts the token, and provides it as a cookie for subsequent API requests.
```python
from scythe.auth import CookieJWTAuth
from scythe.journeys.base import Journey, Step
from scythe.journeys.actions import ApiRequestAction
from scythe.journeys.executor import JourneyExecutor
auth = CookieJWTAuth(
login_url="http://localhost:8080/api/login",
username="user@example.com",
password="secret",
username_field="email",
password_field="password",
jwt_json_path="auth.jwt",
cookie_name="stellarbridge",
)
step = Step(
name="Profile",
description="Protected endpoint",
actions=[ApiRequestAction(method="GET", url="/api/profile", expected_status=200)],
)
journey = Journey(name="Cookie API", description="", steps=[step], authentication=auth)
results = JourneyExecutor(journey, target_url="http://localhost:8080", mode="API").run()
print("Overall:", results.get("overall_success"))
```
--------------------------------
### Form Field Injection with TTPExecutor
Source: https://github.com/epyklab/scythe/blob/master/docs/GETTING_STARTED.md
Demonstrates how to use InputFieldInjector for form field injection and execute it using TTPExecutor. This TTP targets a specific input field within a form on a given URL.
```python
form_sql_ttp = InputFieldInjector(
target_url="http://example.com/search",
field_selector="input[name='query']",
submit_selector="button[type='submit']",
payload_generator=sql_payloads
)
executor = TTPExecutor(ttp=form_sql_ttp, target_url="http://example.com/search")executor.run()
```
--------------------------------
### Implement Machine Behavior in Scythe
Source: https://github.com/epyklab/scythe/blob/master/docs/GETTING_STARTED.md
Configures machine-like behavior for TTPs, characterized by fast, consistent execution and automatic retries. This is ideal for automation where speed and reliability are prioritized. It uses the 'MachineBehavior' class from scythe.behaviors.
```python
from scythe.behaviors import MachineBehavior
# Create machine behavior
machine_behavior = MachineBehavior(
delay=0.5, # Fast, consistent timing
max_retries=5, # Retry failed attempts
fail_fast=True # Stop on critical errors
)
executor = TTPExecutor(
ttp=login_ttp,
target_url="http://example.com/login",
behavior=machine_behavior
)
```
--------------------------------
### Create Wordlist Payload Generator in Scythe
Source: https://github.com/epyklab/scythe/blob/master/docs/GETTING_STARTED.md
Loads payloads from a specified file, assuming one payload per line. This is suitable for using large password lists or dictionaries for comprehensive testing. It uses the 'WordlistPayloadGenerator' class from scythe.payloads.generators.
```python
from scythe.payloads.generators import WordlistPayloadGenerator
# Load from file (one payload per line)
wordlist = WordlistPayloadGenerator("wordlists/rockyou.txt")
# Use with TTP
login_ttp = LoginBruteforceTTP(
payload_generator=wordlist,
username="admin",
username_selector="#username",
password_selector="#password",
submit_selector="#submit"
)
```
--------------------------------
### Test Multiple Usernames and Passwords in Scythe
Source: https://github.com/epyklab/scythe/blob/master/docs/GETTING_STARTED.md
Demonstrates how to test various username and password combinations against a login endpoint. It uses static payload generators for both usernames and passwords, iterating through each combination to perform the test. The 'TTPExecutor' runs the 'LoginBruteforceTTP'.
```python
# Create username/password combinations
usernames = StaticPayloadGenerator(["admin", "user", "test"])
passwords = StaticPayloadGenerator(["password", "123456", "admin"])
# Test each username with each password
for username in ["admin", "user", "test"]:
login_ttp = LoginBruteforceTTP(
payload_generator=passwords,
username=username,
username_selector="#username",
password_selector="#password",
submit_selector="#submit"
)
print(f"Testing username: {username}")
executor = TTPExecutor(
ttp=login_ttp,
target_url="http://example.com/login"
)
executor.run()
```
--------------------------------
### CI/CD GitHub Actions Versioning (YAML)
Source: https://github.com/epyklab/scythe/blob/master/docs/VERSION_HEADER_GUIDE.md
An example GitHub Actions workflow snippet that demonstrates how to automatically set the application version using git tags and export it as an environment variable for subsequent deployment steps. This automates version management in a CI/CD pipeline.
```yaml
# GitHub Actions example
- name: Set version header
run: |
VERSION=$(git describe --tags)
echo "APP_VERSION=$VERSION" >> $GITHUB_ENV
- name: Deploy with version
run: |
export APP_VERSION=${{ env.APP_VERSION }}
./deploy.sh
```
--------------------------------
### Scythe Distributed Orchestrator Setup
Source: https://github.com/epyklab/scythe/blob/master/docs/USE_CASES.md
This Python code snippet demonstrates the import of necessary classes for setting up a distributed testing orchestrator within the Scythe framework. It includes `DistributedOrchestrator`, `NetworkProxy`, and `CredentialSet`.
```python
from scythe.orchestrators.distributed import DistributedOrchestrator, NetworkProxy, CredentialSet
```
--------------------------------
### TTPExecutor WebDriver Setup
Source: https://github.com/epyklab/scythe/blob/master/docs/EXECUTOR.md
Describes the WebDriver setup process, which is triggered when `executor.run()` is called. This step involves creating the Chrome WebDriver instance, applying browser options, and logging the initialization status.
```python
executor.run() # Calls _setup_driver()
# - Creates Chrome WebDriver instance
# - Applies browser options
# - Logs initialization status
```
--------------------------------
### Create Static Payload Generator in Scythe
Source: https://github.com/epyklab/scythe/blob/master/docs/GETTING_STARTED.md
Generates payloads from a predefined list of values. This is useful for testing with known inputs, such as common passwords or specific strings. The 'StaticPayloadGenerator' class from scythe.payloads.generators is used.
```python
from scythe.payloads.generators import StaticPayloadGenerator
# Simple list
passwords = StaticPayloadGenerator([
"password", "123456", "admin"
])
# Mixed data types
mixed_payloads = StaticPayloadGenerator([
"string_payload",
123,
{"key": "value"}
])
```
--------------------------------
### Initiate Distributed Testing Setup
Source: https://github.com/epyklab/scythe/blob/master/docs/README.md
This Python snippet provides the initial setup for distributed testing using Scythe. It imports the `DistributedOrchestrator` and `NetworkProxy` classes, which are foundational components for managing tests across multiple machines or network locations. Further configuration would be required to define the test tasks and network topology.
```python
from scythe.orchestrators.distributed import DistributedOrchestrator, NetworkProxy
# Placeholder for distributed testing setup
# Actual implementation would involve configuring orchestrators and proxies
```
--------------------------------
### Implement Human Behavior in Scythe
Source: https://github.com/epyklab/scythe/blob/master/docs/GETTING_STARTED.md
Creates human-like behavior for TTPs by introducing delays, variance, and mouse movements. This makes automated tests appear more like real user interactions, potentially evading detection. It requires the 'HumanBehavior' class from scythe.behaviors.
```python
from scythe.behaviors import HumanBehavior
# Create human-like behavior
human_behavior = HumanBehavior(
base_delay=2.0, # Base time between actions
delay_variance=1.0, # Random variance in timing
mouse_movement=True, # Random mouse movements
typing_delay=0.1 # Delay between keystrokes
)
# Use with executor
executor = TTPExecutor(
ttp=login_ttp,
target_url="http://example.com/login",
behavior=human_behavior
)
```
--------------------------------
### Granting Execute Permissions to Google Chrome
Source: https://github.com/epyklab/scythe/blob/master/docs/GETTING_STARTED.md
A bash command to change the file permissions of the Google Chrome executable. This is typically used to resolve 'permission denied' errors when the system cannot execute the Chrome binary.
```bash
# Ensure Chrome can be executed
sudo chmod +x /usr/bin/google-chrome
```
--------------------------------
### Perform Form Field Injection in Scythe
Source: https://github.com/epyklab/scythe/blob/master/docs/GETTING_STARTED.md
This snippet is intended for form field injection testing using the 'InputFieldInjector' class. However, the provided code is incomplete and only shows the import statement. Further implementation details are missing.
```python
from scythe.ttps.web.sql_injection import InputFieldInjector
```
--------------------------------
### API Mode Opt-in Example
Source: https://github.com/epyklab/scythe/blob/master/docs/CHANGELOG_API_MODE.md
Demonstrates how to instantiate a TTP (LoginBruteforceTTP) to utilize API mode.
```APIDOC
## API Mode Opt-in Example
### Description
This example shows how to configure the `LoginBruteforceTTP` to use the new API mode.
### Request Example
```python
ttp = LoginBruteforceTTP(
payload_generator=passwords,
username='admin',
execution_mode='api', # Enable API mode
api_endpoint='/api/auth/login', # API endpoint
username_field='username', # JSON field names
password_field='password'
)
```
```
--------------------------------
### Scythe CLI Project Management Commands
Source: https://context7.com/epyklab/scythe/llms.txt
Provides examples of essential Scythe Command Line Interface (CLI) commands for project initialization, test creation, test execution with arguments, and database dumping.
```bash
# Initialize Scythe project
scythe init --path ./my_tests
# Creates ./.scythe/scythe.db and ./.scythe/scythe_tests/
# Create new test
scythe new login_test
# Creates ./.scythe/scythe_tests/login_test.py from template
# Run test with arguments
scythe run login_test -- --url http://localhost:8080 --username admin
# Dump database
scythe db dump
# Returns JSON: {"tests": [...], "runs": [...]}
```
--------------------------------
### Example Usage of LoginBruteforceTTP
Source: https://github.com/epyklab/scythe/blob/master/docs/API_REFERENCE.md
Demonstrates how to instantiate and configure the LoginBruteforceTTP. It shows the creation of a static password generator and passing it along with necessary selectors and username to the TTP constructor.
```python
from scythe.ttps.web.login_bruteforce import LoginBruteforceTTP
from scythe.payloads.generators import StaticPayloadGenerator
# Define a generator for password payloads
passwords = StaticPayloadGenerator(["password", "admin", "123456"])
# Instantiate the LoginBruteforceTTP
login_ttp = LoginBruteforceTTP(
payload_generator=passwords,
username="admin",
username_selector="#username",
password_selector="#password",
submit_selector="#submit"
)
```
--------------------------------
### Install Scythe Library using pip
Source: https://github.com/epyklab/scythe/blob/master/README.md
Installs the Scythe package into a virtual environment using pip. This is the recommended method for using Scythe as a library in your projects. Ensure a virtual environment is activated before running the command.
```bash
python3 -m venv venv
# source the venv
# bash,zsh: source venv/bin/activate
# fish: source venv/bin/activate.fish
# in an activated venv
pip3 install scythe-ttp
```
--------------------------------
### Test User Registration Flow with Journey
Source: https://github.com/epyklab/scythe/blob/master/docs/USE_CASES.md
This snippet defines and executes a multi-step user registration workflow using the Journey class. It includes steps for account creation, email verification, profile setup, and initial application use, with human-like behavior for realistic timing.
```python
# Comprehensive user registration and onboarding
registration_journey = Journey(
name="User Registration and Onboarding",
description="Complete new user workflow from registration to first use"
)
# Step 1: Registration form
registration_step = Step("Account Registration", "Create new user account")
registration_step.add_action(NavigateAction(url="http://app.com/register"))
registration_step.add_action(FillFormAction(field_data={
"#email": "test_{execution_id}@example.com",
"#password": "SecurePassword123!",
"#confirm_password": "SecurePassword123!",
"#first_name": "Test",
"#last_name": "User",
"#terms_accepted": True
}))
registration_step.add_action(ClickAction(selector="#register-button"))
registration_step.add_action(AssertAction(
assertion_type="page_contains",
expected_value="registration successful"
))
# Step 2: Email verification simulation
verification_step = Step("Email Verification", "Verify email address")
verification_step.add_action(WaitAction(wait_type="time", duration=2)) # Simulate email delay
verification_step.add_action(NavigateAction(url="http://app.com/verify?token=auto_generated"))
verification_step.add_action(AssertAction(
assertion_type="url_contains",
expected_value="verified"
))
# Step 3: Profile completion
profile_step = Step("Profile Setup", "Complete user profile")
profile_step.add_action(NavigateAction(url="http://app.com/profile/setup"))
profile_step.add_action(FillFormAction(field_data={
"#company": "Test Company",
"#job_title": "Software Engineer",
"#phone": "+1-555-0123",
"#preferences": "email_notifications"
}))
profile_step.add_action(ClickAction(selector="#save-profile"))
# Step 4: First application use
first_use_step = Step("First Application Use", "Test initial user experience")
first_use_step.add_action(NavigateAction(url="http://app.com/dashboard"))
first_use_step.add_action(ClickAction(selector="#welcome-tour-start"))
first_use_step.add_action(WaitAction(wait_type="element_present", selector=".tour-complete"))
registration_journey.add_step(registration_step)
registration_journey.add_step(verification_step)
registration_journey.add_step(profile_step)
registration_journey.add_step(first_use_step)
# Execute with realistic timing
executor = JourneyExecutor(
journey=registration_journey,
target_url="http://app.com",
behavior=HumanBehavior(base_delay=3.0, delay_variance=2.0)
)
result = executor.run()
```
--------------------------------
### Perform SQL Injection Testing in Scythe
Source: https://github.com/epyklab/scythe/blob/master/docs/GETTING_STARTED.md
Executes SQL injection test cases against a target URL's query parameters. It utilizes a 'StaticPayloadGenerator' for SQL injection payloads and the 'URLManipulation' class for performing the injection. The 'TTPExecutor' runs the SQL injection test.
```python
from scythe.ttps.web.sql_injection import URLManipulation
# SQL injection payloads
sql_payloads = StaticPayloadGenerator([
"' OR '1'='1",
"' OR '1'='1' --",
"' UNION SELECT NULL--",
"'; DROP TABLE users; --"
])
# Test URL parameter injection
sql_ttp = URLManipulation(
payload_generator=sql_payloads,
target_url="http://example.com/search"
)
executor = TTPExecutor(
ttp=sql_ttp,
target_url="http://example.com/search"
)
executor.run()
```
--------------------------------
### Scythe API Schema Validation with Pydantic
Source: https://github.com/epyklab/scythe/blob/master/docs/GETTING_STARTED.md
Shows how to validate API response JSON against a Pydantic model within Scythe's API mode by passing a response_model to ApiRequestAction. This ensures responses conform to expected structures.
```python
from pydantic import BaseModel
from scythe.journeys.base import Journey, Step
from scythe.journeys.actions import ApiRequestAction
from scythe.journeys.executor import JourneyExecutor
class Health(BaseModel):
status: str
version: str | None = None
step = Step(
name="Health",
description="GET /api/health returns 200 and valid schema",
actions=[
ApiRequestAction(
method="GET",
url="/api/health",
expected_status=200,
response_model=Health,
response_model_context_key="health_model",
fail_on_validation_error=True,
)
],
)
journey = Journey(name="API Schema Smoke", description="Schema check", steps=[step])executor = JourneyExecutor(journey=journey, target_url="http://localhost:8080", mode="API")
results = executor.run()
print("Overall:", results.get("overall_success"))
```
--------------------------------
### Clone Scythe Repository and Install Dependencies
Source: https://github.com/epyklab/scythe/blob/master/README.md
Clones the Scythe project repository from GitHub and installs development dependencies. This is for users who wish to contribute to the project. It requires Git and Python to be installed.
```bash
git clone https://github.com/EpykLab/scythe.git
cd scythe
pip install -r requirements.txt
```
--------------------------------
### Verify Scythe Installation
Source: https://github.com/epyklab/scythe/blob/master/README.md
Verifies that Scythe has been successfully installed by importing the TTP class and printing a success message. This command should be run after installing Scythe via pip or from source.
```python
python -c "from scythe.core.ttp import TTP; print('✅ Scythe installed successfully')"
```
--------------------------------
### Implement Stealth Behavior in Scythe
Source: https://github.com/epyklab/scythe/blob/master/docs/GETTING_STARTED.md
Enables stealthy TTP execution by employing randomized delays and limiting requests per session. This behavior aims to evade detection systems by mimicking erratic user activity and avoiding high-volume requests. It utilizes the 'StealthBehavior' class from scythe.behaviors.
```python
from scythe.behaviors import StealthBehavior
# Create stealth behavior
stealth_behavior = StealthBehavior(
min_delay=5.0, # Minimum delay between actions
max_delay=15.0, # Maximum delay
long_pause_probability=0.2, # Chance of long pauses
max_requests_per_session=10 # Limit requests per session
)
executor = TTPExecutor(
ttp=login_ttp,
target_url="http://example.com/login",
behavior=stealth_behavior
)
```
--------------------------------
### Run Scythe Tests with Version Detection
Source: https://github.com/epyklab/scythe/blob/master/docs/VERSION_HEADER_GUIDE.md
An example of a Scythe test case that utilizes Scythe's automatic version detection. This Python code defines a custom TTP (Test Type Pattern) and uses TTPExecutor to run the test. Scythe automatically associates the test results with the version reported via the X-SCYTHE-TARGET-VERSION header.
```python
from scythe.core.ttp import TTP
from scythe.core.executor import TTPExecutor
class MyTTP(TTP):
def get_payloads(self):
yield "test_payload"
def execute_step(self, driver, payload):
driver.get("http://your-app.com")
def verify_result(self, driver):
return "welcome" in driver.page_source
ttp = MyTTP("Test", "Description")
executor = TTPExecutor(ttp=ttp, target_url="http://your-app.com")executor.run()
```
--------------------------------
### MachineBehavior Configuration in Scythe Framework (Python)
Source: https://github.com/epyklab/scythe/blob/master/docs/BEHAVIORS.md
Illustrates the setup of MachineBehavior, suitable for automated testing with consistent timing. It allows configuration of fixed delays, retries, and a fail-fast option for critical errors.
```python
from scythe.behaviors import MachineBehavior
behavior = MachineBehavior(
delay=0.5, # Fixed delay between actions
max_retries=5, # Maximum retries on failure
retry_delay=1.0, # Fixed delay between retries
fail_fast=True # Stop on critical errors
)
```
--------------------------------
### HeaderExtractor Usage (Python)
Source: https://github.com/epyklab/scythe/blob/master/docs/VERSION_HEADER_GUIDE.md
Demonstrates how to use the HeaderExtractor class to extract version and all headers from a driver instance, and process the results. Requires the scythe.core.headers module.
```python
from scythe.core.headers import HeaderExtractor
extractor = HeaderExtractor()
# Extract version header
version = extractor.extract_target_version(driver, target_url=None)
# Extract all headers
headers = extractor.extract_all_headers(driver, target_url=None)
# Get version summary from results
summary = extractor.get_version_summary(results)
# Enable logging (call during WebDriver setup)
HeaderExtractor.enable_logging_for_driver(chrome_options)
```
--------------------------------
### Result and Version Summary Structures (JSON)
Source: https://github.com/epyklab/scythe/blob/master/docs/VERSION_HEADER_GUIDE.md
Illustrates the JSON structure for test results, including a new 'target_version' field, and the structure for a version summary report.
```json
{
'payload': 'test_data',
'url': 'http://example.com/page',
'expected': True,
'actual': True,
'target_version': '1.3.2' # New field
}
```
```json
{
'total_results': 5,
'results_with_version': 4,
'unique_versions': ['1.3.2', '1.3.1'],
'version_counts': {
'1.3.2': 3,
'1.3.1': 1
}
}
```
--------------------------------
### Scythe Project Directory Structure
Source: https://github.com/epyklab/scythe/blob/master/docs/README.md
This snippet outlines the directory structure of the Scythe project, showing the organization of core framework code, documentation, examples, and tests. It helps developers understand where to find specific components.
```tree
scythe/
├── scythe/ # Core framework code
│ ├── core/ # TTPs and execution engine
│ ├── journeys/ # Multi-step workflow framework
│ ├── orchestrators/ # Scale and distribution management
│ ├── auth/ # Authentication systems
│ ├── behaviors/ # Execution pattern control
│ └── payloads/ # Test data generation
├── docs/ # Documentation
├── examples/ # Real-world examples
└── tests/ # Comprehensive test suite
```
--------------------------------
### Python OAuth 2.0 Authentication Example with Selenium
Source: https://github.com/epyklab/scythe/blob/master/docs/DEVELOPER_GUIDE.md
Provides an example implementation for OAuth 2.0 authentication using Python and Selenium. This snippet outlines the initial steps of the OAuth flow, including navigating to the authorization URL. Full implementation of consent handling and token exchange would depend on the specific OAuth provider and flow.
```python
class OAuth2Auth(Authentication):
def __init__(self, client_id: str, client_secret: str, redirect_uri: str):
super().__init__(
name="OAuth 2.0 Authentication",
description="OAuth 2.0 flow authentication"
)
self.client_id = client_id
self.client_secret = client_secret
self.redirect_uri = redirect_uri
self.access_token = None
def authenticate(self, driver: WebDriver, target_url: str) -> bool:
try:
# Step 1: Navigate to OAuth authorization URL
auth_url = f"{target_url}/oauth/authorize?client_id={self.client_id}&redirect_uri={self.redirect_uri}&response_type=code"
driver.get(auth_url)
# Step 2: Handle OAuth consent (implementation depends on provider)
# This would typically involve clicking consent buttons
# Step 3: Extract authorization code from redirect
# Implementation depends on OAuth flow
# Step 4: Exchange code for access token
# This would typically be done via HTTP request
return True
except Exception as e:
raise AuthenticationError(f"OAuth authentication failed: {str(e)}")
```
--------------------------------
### TTPExecutor Initialization Phase
Source: https://github.com/epyklab/scythe/blob/master/docs/EXECUTOR.md
Illustrates the initialization phase of the TTPExecutor, which occurs before `run()` is called. This phase involves parameter validation, Chrome options setup, logging initialization, and result collection preparation.
```python
executor = TTPExecutor(ttp=my_ttp, target_url="http://example.com")
# - Validates parameters
# - Sets up Chrome options
# - Initializes logging
# - Prepares result collection
```
--------------------------------
### TTPExecutor Pre-Execution Behavior
Source: https://github.com/epyklab/scythe/blob/master/docs/EXECUTOR.md
Outlines the pre-execution phase when a behavior is specified. This involves calling the behavior's `pre_execution` method to perform setup, browser configuration, and initial page preparation.
```python
# If behavior is specified:
behavior.pre_execution(driver, target_url) # Assumes driver and target_url are available
# - Behavior-specific setup
# - Browser configuration
# - Initial page preparation
```
--------------------------------
### Perform REST Call with ApiRequestAction
Source: https://github.com/epyklab/scythe/blob/master/docs/API_REFERENCE.md
An example of using ApiRequestAction to perform a GET request to an API endpoint as part of a Scythe Journey step. This action is designed for API mode execution.
```python
from scythe.journeys.base import Journey, Step
from scythe.journeys.actions import ApiRequestAction
from scythe.journeys.executor import JourneyExecutor
step = Step(
name="Health",
description="Backend health should be OK",
actions=[ApiRequestAction(method="GET", url="/api/health", expected_status=200)],
)
journey = Journey(name="API Smoke", description="Simple API smoke test", steps=[step])
executor = JourneyExecutor(journey=journey, target_url="http://localhost:8080", mode="API")
results = executor.run()
assert results["overall_success"] is True
```
--------------------------------
### Scythe CLI
Source: https://context7.com/epyklab/scythe/llms.txt
Utilize the Scythe Command Line Interface for project initialization, test creation, and execution.
```APIDOC
## Scythe CLI
### Description
Built-in command-line interface for workspace management and test execution.
### Commands
#### `scythe init`
- **Description**: Initializes a new Scythe project.
- **Usage**: `scythe init --path `
- **Example**: `scythe init --path ./my_tests`
- **Effect**: Creates `.scythe/scythe.db` and `.scythe/scythe_tests/` directories.
#### `scythe new`
- **Description**: Creates a new test file from a template.
- **Usage**: `scythe new `
- **Example**: `scythe new login_test`
- **Effect**: Creates `.py` in the `scythe_tests` directory.
#### `scythe run`
- **Description**: Executes a specified test.
- **Usage**: `scythe run [-- ]`
- **Example**: `scythe run login_test -- --url http://localhost:8080 --username admin`
- **Note**: Arguments after `--` are passed directly to the test.
#### `scythe db dump`
- **Description**: Dumps the contents of the Scythe database.
- **Usage**: `scythe db dump`
- **Effect**: Returns JSON output containing test and run history data.
```
--------------------------------
### Configuration Management from JSON File in Python
Source: https://github.com/epyklab/scythe/blob/master/docs/EXECUTOR.md
This Python code provides a class method `from_config` for `ConfigurableTTPExecutor` that allows creating an executor instance from a JSON configuration file. The method reads the configuration, dynamically loads the specified TTP and behavior classes (if any), and instantiates them with their respective parameters. It then initializes the `ConfigurableTTPExecutor` with the loaded components and other executor-specific parameters from the config. This promotes modularity and simplifies the setup of complex TTP executions.
```python
# Use configuration files for complex setups
import json
class ConfigurableTTPExecutor(TTPExecutor):
@classmethod
def from_config(cls, config_path: str):
"""Create executor from configuration file."""
with open(config_path, 'r') as f:
config = json.load(f)
# Create TTP from config
ttp_class = getattr(ttps, config['ttp']['class'])
ttp = ttp_class(**config['ttp']['params'])
# Create behavior from config
behavior = None
if 'behavior' in config:
behavior_class = getattr(behaviors, config['behavior']['class'])
behavior = behavior_class(**config['behavior']['params'])
return cls(
ttp=ttp,
target_url=config['target_url'],
behavior=behavior,
**config.get('executor_params', {})
)
# Usage with config fileexecutor = ConfigurableTTPExecutor.from_config('ttp_config.json')executor.run()
```
--------------------------------
### Define Healthcare System Compliance Test Journey
Source: https://github.com/epyklab/scythe/blob/master/README.md
An example of initializing a `Journey` object in Scythe for HIPAA-compliant healthcare system testing. This serves as a starting point for defining specific compliance tests within the healthcare domain.
```python
from scythe.journeys.base import Journey
# HIPAA-compliant healthcare system testing
healthcare_journey = Journey("Healthcare System Compliance Test")
```
--------------------------------
### Run Scythe Tests (Bash)
Source: https://github.com/epyklab/scythe/blob/master/docs/VERSION_HEADER_GUIDE.md
Executes Scythe tests against a running test server. This command verifies that Scythe correctly identifies and interacts with the version header exposed by the test server. Ensure the test server is running before executing this command.
```bash
# Run Scythe tests against it
python examples/version_header_example.py http://localhost:8080
```
--------------------------------
### Basic Human Behavior Usage in Python
Source: https://github.com/epyklab/scythe/blob/master/BEHAVIORS_SUMMARY.md
Demonstrates how to instantiate and use the HumanBehavior class with a TTPExecutor. It showcases setting base delay and mouse movement options, then running the executor.
```python
from scythe.behaviors import HumanBehavior
behavior = HumanBehavior(base_delay=2.0, mouse_movement=True)
executor = TTPExecutor(ttp=my_ttp, target_url="http://target.com", behavior=behavior)
executor.run()
```
--------------------------------
### Set X-SCYTHE-TARGET-VERSION Header in PHP
Source: https://github.com/epyklab/scythe/blob/master/docs/VERSION_HEADER_GUIDE.md
Demonstrates adding the X-SCYTHE-TARGET-VERSION header in PHP. It includes a global approach by directly setting the header at the top of a PHP file, and an example for frameworks like Laravel using middleware. The header indicates the application's version.
```php
// Global header (at the top of your main PHP file)
header('X-SCYTHE-TARGET-VERSION: 1.3.2');
// Or in a framework like Laravel (middleware)
class VersionHeaderMiddleware
{
public function handle($request, Closure $next)
{
$response = $next($request);
$response->headers->set('X-SCYTHE-TARGET-VERSION', '1.3.2');
return $response;
}
}
```
--------------------------------
### Set X-SCYTHE-TARGET-VERSION Header in Java/Spring Boot
Source: https://github.com/epyklab/scythe/blob/master/docs/VERSION_HEADER_GUIDE.md
Provides examples for adding the X-SCYTHE-TARGET-VERSION header in a Java Spring Boot application. It illustrates both a global approach using a Filter and a controller-level implementation for specific endpoints. The header value signifies the application's version.
```java
// Global filter approach
@Component
public class VersionHeaderFilter implements Filter {
@Value("${app.version:1.3.2}")
private String appVersion;
@Override
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
HttpServletResponse httpResponse = (HttpServletResponse) response;
httpResponse.setHeader("X-SCYTHE-TARGET-VERSION", appVersion);
chain.doFilter(request, response);
}
}
// Alternative: Controller-level implementation
@RestController
public class ApiController {
@Value("${app.version}")
private String appVersion;
@GetMapping("/api/data")
public ResponseEntity