Skip to main content

A data mocking tool designed to help you generate realistic data for testing and development purposes.

Project description

PistolMagazine 🎯

PyPI - Version

PistolMagazine is a data mocking tool designed to help you generate realistic data for testing and development purposes.

Features ✨

  • Flexible Data Types 📊: Supports various data types including integers, floats, strings, timestamps, and more.
  • Custom Providers 🛠️: Easily create and integrate custom data providers.
    • Built-in Providers 🏗️: Provides several built-in providers for common use cases.
  • Random Data Generation 🎲: Generates realistic random data for testing.
  • Hook Functions 🪝: Support for hook functions, allowing users to execute custom operations before or after generating mock data. These hooks can be utilized for:
    • Logging: Record relevant operations or data before or after data generation.
    • Starting External Services: Initiate external services or resources before generating data.
    • Dynamic Data Modification: Perform data validation or sanitization before generating mock data.
    • Sending Data to Message Queues: Transmit generated data to message queues for integration with other systems.
    • Data Profiling: Perform statistical analysis or monitoring post data generation.
  • Data Export 📤: Supports exporting to CSV, JSON, XML, and MySQL. Can be used in conjunction with hook functions.

Installation 📦

Install PistolMagazine using pip:

pip install PistolMagazine

Quick Start 🚀

Here’s a quick example to get you started:

You can use the pistol-gen command to interactively select a sample code template and specify the path for the generated code within your project directory.

Run the following command:

pistol-gen

The tool will then generate the file with the chosen template at the specified location.

from random import choice
from pistol_magazine import *


# Create a custom provider
@provider
class MyProvider:
    def my_provider(self):
        return choice(["ACTIVE", "INACTIVE"])


"""
Define hook functions
pre_generate: Executes operations before generating all data. Suitable for tasks like logging or starting external services.
after_generate: Executes operations after generating each data entry but before final processing. Suitable for tasks like data validation or conditional modifications.
final_generate: Executes operations after generating and processing all data entries. Suitable for final data processing, sending data to message queues, or performing statistical analysis.
"""
@hook('pre_generate', order=1, hook_set='SET1')
def pre_generate_first_hook():
    print("Start Mocking User Data")


@hook('pre_generate', order=2, hook_set='SET1')
def pre_generate_second_hook():
    """
    Perform some preprocessing operations, such as starting external services.
    """

@hook('after_generate', order=1, hook_set="SET1")
def after_generate_first_hook(data):
    data['customized_param'] = 'ACTIVE' if data['int_param'] >= 18 else 'INACTIVE'
    return data


@hook('final_generate', order=1, hook_set="SET1")
def final_generate_second_hook(data):
    """
    Suppose there is a function send_to_message_queue(data) to send data to the message queue
    Or use built-in data exporters to export data, like the code below⬇️.
    """
    json_exporter = JSONExporter()  # Also support csv, db, xml export
    json_exporter.export(data, 'output.json')


class Temp(DataMocker):
    timestamp_param: Timestamp = Timestamp(Timestamp.D_TIMEE10, days=2)
    str_param1: Str = Str(data_type="name")
    str_param2: Str = Str(data_type="email")
    int_param: Int = Int(byte_nums=6, unsigned=True)
    customized_param: ProviderField = ProviderField(MyProvider().my_provider)
    bool_param: Bool = Bool()
    dict_param: Dict = Dict(
        {
            "a": Float(left=2, right=4, unsigned=True),
            "b": Timestamp(Timestamp.D_TIMEE10, days=2)
        }
    )
    list_param: List = List(
        [
            Datetime(Datetime.D_FORMAT_YMD_T, weeks=2),
            StrInt(byte_nums=6, unsigned=True)
        ]
    )
    built_in_provider_param1: ProviderField = ProviderField(
        CyclicParameterProvider(parameter_list=["x", "y", "z"]).gen
    )
    built_in_provider_param2: ProviderField = ProviderField(
        RandomFloatInRangeProvider(start=0.00, end=4.00, precision=4).gen
    )
    built_in_provider_param3: ProviderField = ProviderField(
        IncrementalValueProvider(start=0, step=-2).gen
    )
    built_in_provider_param4: ProviderField = ProviderField(
        RegexProvider(pattern=r"\d{3}-[a-z]{2}").gen
    )
    fixed_value_str = "fixed_value"
    fixed_value_dict = {"key": "value"}

    def gen_data(self):
        return self.mock(
            num_entries=3,
            as_list=False,
            to_json=True,
            hook_set='SET1',
            key_generator=lambda: RegexProvider(pattern=r"^[A-Z]{4}-\d{3}$").gen()
        )


if __name__ == '__main__':
    print(Temp().gen_data())

If you want more detailed instructions, you can refer to the examples and documentation in the wiki.

Help PistolMagazine

If you find PistolMagazine useful, please ⭐️ Star it at GitHub

Feature discussions and bug reports are also welcome!

Happy Mocking! 🎉🎉🎉

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

PistolMagazine-0.8.2.tar.gz (19.9 kB view details)

Uploaded Source

Built Distribution

PistolMagazine-0.8.2-py3-none-any.whl (32.1 kB view details)

Uploaded Python 3

File details

Details for the file PistolMagazine-0.8.2.tar.gz.

File metadata

  • Download URL: PistolMagazine-0.8.2.tar.gz
  • Upload date:
  • Size: 19.9 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/5.1.0 CPython/3.9.9

File hashes

Hashes for PistolMagazine-0.8.2.tar.gz
Algorithm Hash digest
SHA256 5b7bb5a401bc0af703d2ecaf559a75f33778f5178ce54dd9a44157148984ee96
MD5 bf3e10027995087034e860a6d99ddb87
BLAKE2b-256 00058e4ce0790bdee9c3778e41181dc13116fa886dc6819688bf06aa09baf733

See more details on using hashes here.

File details

Details for the file PistolMagazine-0.8.2-py3-none-any.whl.

File metadata

File hashes

Hashes for PistolMagazine-0.8.2-py3-none-any.whl
Algorithm Hash digest
SHA256 60ea206fd2893fae59dea59241e5e2413a3215c20d52a5cc66581dd14c78b10a
MD5 f483be14ff72e127580171d7164fee13
BLAKE2b-256 84961ba6cd38940c0c4632b864779681c3809dd2e40c26a05dc36e2a980170c5

See more details on using hashes here.

Supported by

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