Skip to main content

Probabilistic proxy for injecting randomness into Python objects

Project description

ChaosInjector 🚀

PyPI version

License: MIT

Downloads

Inject Chaos, Control Uncertainty – Revolutionize Your Python Code with Probabilistic Proxies!

Imagine turning any Python object into a probabilistic powerhouse: methods that "flake out" randomly, logs that sample themselves, tests that simulate real-world failures without a single line of mocking code. ChaosInjector is the ultimate tool for developers who crave dynamic, resilient, and innovative code. Whether you're hardening your app against flakiness, optimizing performance through sampling, or adding randomness to simulations and games – ChaosInjector makes it effortless and elegant.

Why settle for static code when you can embrace controlled chaos? Join the ranks of forward-thinking devs using ChaosInjector to supercharge testing, logging, AI behaviors, and more. Install now and unlock the power of probability!

Why ChaosInjector? 🔥

In a world of unpredictable systems, ChaosInjector gives you the edge:

  • Fault Injection on Steroids: Simulate flaky networks, databases, or APIs with a single line – perfect for robust unit/integration tests.
  • Performance Sampling Magic: Reduce overhead in logging, tracing, or analytics by executing only X% of the time.
  • Stochastic Simulations: Add realistic randomness to games, ML models, or Monte Carlo methods without rewriting logic.
  • A/B Testing Simplified: Roll out features probabilistically, no complex infra needed.
  • Privacy & Security Boost: Anonymize sensitive data accesses randomly for compliance and honeypots.

Built with Python's dynamic magic (runtime class proxying via __getattribute__), ChaosInjector is lightweight, zero-dependency, and battle-tested with full coverage. It's not just a library – it's your secret weapon for smarter, more adaptive code.

Quick Start ⚡

Installation

Get started in seconds:

pip install chaosinjector

Basic Usage

Suppress logs probabilistically? Easy!

import logging
from chaosinjector import ChaosInjector


logger = logging.getLogger("my_app")
ChaosInjector.inject(logger, probability=0.1)  # Only 10% chance logs execute

logger.info("This might not log!")  # Flaky by design!

Want more control? Use deciders or per-method probs:

ChaosInjector.inject(
    logger, method_probs={"info": 0.0, "error": 1.0}
)  # Info always skipped, errors always log

Or custom logic:

ChaosInjector.inject(
    logger, decider=lambda name: "debug" not in name
)  # Skip all debug methods

Features at a Glance 🌟

  • Probabilistic Attribute Access: Return real attributes/methods with tunable probability (0.0-1.0).
  • Custom Deciders: Pass a callable to decide per-attribute (e.g., based on name, env vars, or time).
  • Per-Method Granularity: Dict of method-specific probabilities for fine-tuned control.
  • Safe No-Op Handling: Callables become silent lambdas; non-callables return None – no crashes!
  • Validation Built-In: Ensures probabilities are valid (0-1), preventing silent errors.
  • Lightweight & Pure Python: No dependencies, works with Python 3.8+.
  • Extensively Tested: 100% coverage with pytest, including mocked randomness for determinism.

Real-World Examples 💡

1. Fault Injection in Tests

Simulate unreliable services:

import requests
from chaosinjector import ChaosInjector


session = requests.Session()
ChaosInjector.inject(session, probability=0.3)  # 70% failure rate

response = session.get(
    "https://api.example.com"
)  # Often None – test your retries!

2. Sampling Expensive Operations

Optimize tracing:

from opentelemetry import trace
from chaosinjector import ChaosInjector


tracer = trace.get_tracer(__name__)
ChaosInjector.inject(tracer, probability=0.1)  # Trace only 10% of calls

with tracer.start_as_current_span("operation"):  # Sometimes no-op
    pass

3. Probabilistic AI in Games

Add unpredictability:

class NPC:
    def attack(self):
        print("Boom!")


npc = NPC()
ChaosInjector.inject(
    npc, method_probs={"attack": 0.7}
)  # Attacks 70% of the time

npc.attack()  # Maybe... maybe not!

4. Data Privacy Masking

Anonymize sensitive fields:

class UserData:
    user_id = "sensitive123"


data = UserData()
ChaosInjector.inject(
    data, decider=lambda name: name != "user_id"
)  # user_id always None

print(data.user_id)  # None – protected!

Explore more in our docs (coming soon)!

Contributing 🤝

Love ChaosInjector? Help make it better! Fork the repo, add features/tests, and submit a PR.

  • Report issues: GitHub Issues
  • Star the repo: ⭐️
  • Spread the word: Share on X or Reddit!

License 📄

Released under the MIT License. Free to use, modify, and distribute.


Ready to Prob-ify your code? Install ChaosInjector today and turn uncertainty into your superpower. Questions? Hit us up in issues – we're here to help! 🚀

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

chaosinjector-0.1.0.tar.gz (6.6 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

chaosinjector-0.1.0-py3-none-any.whl (6.1 kB view details)

Uploaded Python 3

File details

Details for the file chaosinjector-0.1.0.tar.gz.

File metadata

  • Download URL: chaosinjector-0.1.0.tar.gz
  • Upload date:
  • Size: 6.6 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.1.0 CPython/3.10.6

File hashes

Hashes for chaosinjector-0.1.0.tar.gz
Algorithm Hash digest
SHA256 c1616b3e095892df0ddc40dcc1187ea6bc89b8fbfbd6a23bc269a2385f2e2640
MD5 f12ed80a04c9d873227e574fb5541c90
BLAKE2b-256 ef7fb0d88ab18431f82612a2a1b558e9340838418aac2db70429d3a419458170

See more details on using hashes here.

File details

Details for the file chaosinjector-0.1.0-py3-none-any.whl.

File metadata

  • Download URL: chaosinjector-0.1.0-py3-none-any.whl
  • Upload date:
  • Size: 6.1 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.1.0 CPython/3.10.6

File hashes

Hashes for chaosinjector-0.1.0-py3-none-any.whl
Algorithm Hash digest
SHA256 baa9b6859cc52a732f351f86a81c7e29803818e4a154302db7c7fd81459f8602
MD5 0cbd627a8323fc8a0d1e33002b22da5d
BLAKE2b-256 281c11fc39b5e26b408bf4b40dffb73ac0b774472f97ff90cdac0a31221549eb

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page