But note: we might want to store the generated data and then later create subsets from it without regenerating.
Let's think about the requirements:
We want to generate test data (maybe large volumes) and then be able to get subsets for testing.
We want to anonymize sensitive data (like PII) so that the test data is safe.
We want to refresh the data periodically (e.g., every day) to keep it up-to-date.
We can design:
class DataManager:
def init(self, generator, anonymizer=None, storage=None):
self.generator = generator
self.anonymizer = anonymizer
self.storage = storage # could be a file, database, or in-memory
self.data = None # we can cache the last generated data
code
def generate(self, force=False):
# if we have storage and force is False and data exists, we might load from storage?
# But note: we might want to regenerate even if storage exists if the generator is based on current time.
# Let's assume we always generate new data when generate is called, then we can store it.
data = self.generator.generate()
if self.anonymizer:
data = self.anonymizer.anonymize(data)
if self.storage:
self.storage.save(data)
self.data = data
return data
def get_subset(self, subset_condition):
# subset_condition could be a function that filters rows, or a sampling ratio, etc.
if self.data is None:
self.generate()
# Apply subset condition on self.data
# For simplicity, let's assume self.data is a pandas DataFrame.
# But note: our generator might return different types. We need to standardize.
# We can standardize on pandas DataFrame for in-memory.
subset = self.data[subset_condition(self.data)]
return subset
def refresh(self, schedule=None):
# If schedule is provided, set up a scheduler (like APScheduler) to call generate at intervals.
# Otherwise, just generate now.
self.generate()
However, this design might not be flexible for multiple sources and complex pipelines.
Let's consider a more flexible design:
We have a pipeline of stages. Each stage is a callable that takes data and returns transformed data.
Example pipeline: [Generator, Anonymizer, Subset]
We can have:
code
class Pipeline:
def __init__(self, stages):
self.stages = stages
def run(self, initial_data=None):
data = initial_data
for stage in self.stages:
data = stage.process(data)
return data
Then, each stage (Generator, Anonymizer, Subset) would have a process method.
But note: the Generator doesn't take input data (it generates from scratch). So we can design:
code
class Generator:
def process(self, data=None):
# ignore input and generate new data
return self.generate()
class Anonymizer:
def process(self, data):
return self.anonymize(data)
class Subset:
def process(self, data):
return self.get_subset(data)
Then we can have:
code
pipeline = Pipeline([Generator(...), Anonymizer(...), Subset(...)])
data = pipeline.run()
But what if we want to store the data at an intermediate stage? We might want to cache the generated data before anonymization?
Alternatively, we can design the DataManager to hold the data at each stage and allow re-running from any stage.
However, for simplicity, let's stick to the first design and assume we generate, then anonymize, then subset.
But note: the requirement says "subsets" which might be applied on the stored data (so we don't have to regenerate every time we want a subset).
So let's adjust:
code
We have a data storage that holds the current (generated and anonymized) data.
Then, when we want a subset, we just filter from the stored data.
Steps:
code
1. Generate data (if not exists or forced) -> store it in memory and optionally on disk.
2. Anonymize the generated data and store the anonymized version (or we can store both? but we only need the anonymized for testing).
3. When we need a subset, we take from the stored anonymized data.
But note: we might want to stop the scheduler. So we can store the scheduler as an attribute.
Alternatively, we can let the user set up the scheduler and just call refresh when needed.
Since the requirement says "refresh cadence", we'll provide a way to schedule.
Let's write a simple example without an external scheduler (using a thread and time.sleep) but note that it's better to use a scheduler.
However, to avoid external dependencies, we can make the scheduler optional and if the user wants, they can set up their own.
We'll design:
code
class DataManager:
... as above ...
def start_auto_refresh(self, interval, unit='hours'):
# interval: number of units (hours by default) between refreshes.
# We'll use a background thread that sleeps for interval*3600 seconds and then refreshes.
import threading
import time
def refresh_loop():
while True:
time.sleep(interval * 3600) # convert hours to seconds
self.refresh()
thread = threading.Thread(target=refresh_loop, daemon=True)
thread.start()
But note: this is a simple implementation and might not be precise. Also, if the refresh takes a long time, we might want to avoid overlapping.
We'll leave it as a simple example.
Now, let's define the interfaces for Generator and Anonymizer.
We'll use pandas DataFrames for data representation for simplicity.
Example:
code
class Generator(ABC):
@abstractmethod
def generate(self):
pass
class MockDataGenerator(Generator):
def __init__(self, num_rows, schema):
self.num_rows = num_rows
self.schema = schema # dictionary: column name -> Faker provider or type
def generate(self):
import pandas as pd
from faker import Faker
fake = Faker()
data = {}
for col, provider in self.schema.items():
if callable(provider):
data[col] = [provider() for _ in range(self.num_rows)]
elif isinstance(provider, str):
# Assume it's a Faker provider name
data[col] = [getattr(fake, provider)() for _ in range(self.num_rows)]
else:
# Maybe a type? We can generate random data of that type?
# For simplicity, we'll just use a fixed value or random choice?
# Let's not complicate, we require the schema to be a mapping to callables or faker provider strings.
pass
return pd.DataFrame(data)
class Anonymizer(ABC):
@abstractmethod
def anonymize(self, df):
pass
class MaskingAnonymizer(Anonymizer):
def __init__(self, columns_to_mask, mask_char='*', mask_length=None):
self.columns_to_mask = columns_to_mask
self.mask_char = mask_char
self.mask_length = mask_length
def anonymize(self, df):
for col in self.columns_to_mask:
if col in df.columns:
if self.mask_length:
df[col] = df[col].astype(str).apply(lambda x: x[:self.mask_length] + self.mask_char * (len(x)-self.mask_length) if len(x) > self.mask_length else self.mask_char * len(x))
else:
df[col] = df[col].astype(str).apply(lambda x: self.mask_char * len(x))
return df
class FakerAnonymizer(Anonymizer):
def __init__(self, column_mapping):
# column_mapping: original column -> (faker provider, {kwargs})
self.column_mapping = column_mapping
self.fake = Faker()
def anonymize(self, df):
for col, (provider, kwargs) in self.column_mapping.items():
if col in df.columns:
df[col] = df[col].apply(lambda x: getattr(self.fake, provider)(**kwargs))
return df
For the storage, we can have:
code
class Storage:
def save(self, df):
# save to a file (e.g., CSV, Parquet) or database
pass
def load(self):
# load from storage
pass
def sample(df, n=None, frac=None, random_state=None):
if n is not None:
return df.sample(n=n, random_state=random_state)
elif frac is not None:
return df.sample(frac=frac, random_state=random_state)
But we can let the user pass any function.
So, the get_subset method:
code
def get_subset(self, condition):
data = self.load_data()
if condition is None:
return data
if callable(condition):
mask = condition(data)
return data[mask]
else:
raise ValueError("condition must be a callable that returns a boolean mask")
We can also support a dictionary of conditions? But let's keep it simple.
Now, let's put it all together in an example.
Example usage:
code
# Define schema for mock data generator
schema = {
'name': 'name',
'email': 'email',
'age': lambda: random.randint(18, 80),
'country': 'country'
}
generator = MockDataGenerator(num_rows=1000, schema=schema)
anonymizer = MaskingAnonymizer(columns_to_mask=['email'])
storage = CSVStorage('test_data.csv')
data_manager = DataManager(generator, anonymizer, storage)
# Generate and store (if not already stored, but we'll force)
data_manager.generate_and_store()
# Get subset of people over 30 from the USA
subset = data_manager.get_subset(lambda df: (df['age'] > 30) & (df['country'] == 'USA'))
# Start auto refresh every 24 hours
data_manager.start_auto_refresh(24)
This is a basic design.
Considerations:
We are using pandas. What if the data is too big for pandas? We might need to use Dask or Spark.
The storage might be a database, then we don't want to load everything into memory for subsetting? We might want to push the subset condition to the database.
We can make the storage interface more flexible:
code
class Storage:
def save(self, df):
pass
def load(self, condition=None):
# if condition is provided, load only the subset? But then we are storing the entire data and then filtering.
# Alternatively, we can store and then query. But if we are using a file, we have to load all and then filter.
# If we are using a database, we can query with condition.
So, we can change:
In DataManager.get_subset, we can:
if condition is None:
return self.storage.load()
else:
return self.storage.load(condition)
Then, for CSVStorage, we load all and then filter (inefficient for large files). For a database storage, we can do:
class DBStorage(Storage):
def __init__(self, connection_string, table_name):
...
def load(self, condition=None):
query = f"SELECT * FROM {self.table_name}"
if condition is not None:
# condition is a string? or a callable? We need to convert callable to SQL?
# This is complex. Alternatively, we can accept a string for condition (SQL WHERE clause).
# Let's change the condition to be a string for SQL? But then we lose the flexibility of using a function.
Alternatively, we can have two methods: `load_all` and `load_with_condition` and then in DataManager we decide.
Given the complexity, let's stick to in-memory pandas for now and note that for large data we might need a different approach.
We'll design the storage to return a DataFrame and accept a DataFrame for save.
For the subset, we can also have a method that returns the subset without loading the entire data if the storage supports it.
But to keep it simple, we'll assume the entire dataset fits in memory.
Let's code accordingly.
We'll write:
code
from abc import ABC, abstractmethod
import pandas as pd
from faker import Faker
import random
And then the classes.
However, note: the requirement says "test data management system", so we are building a tool for testers.
We might want to have a configuration file (YAML) to define the generators, anonymizers, and subsets.
But that's beyond the scope of this code.
We'll write the code with the above design.
Let's code accordingly.
Note: We are not handling errors and edge cases for brevity.
Let's write the code in a single block.
We'll break down:
code
1. Abstract base classes for Generator and Anonymizer.
2. MockDataGenerator and CSVDataGenerator (for reading from an existing CSV and then we can anonymize and subset).
3. MaskingAnonymizer and FakerAnonymizer.
4. Storage base and CSVStorage.
5. DataManager.
We'll also include a simple example at the end.
But note: the requirement says "generators, anonymization, subsets, and refresh cadence".
We have all these.
Let's code.
I'll design a comprehensive test data management system with generators, anonymization, subsets, and refresh cadence capabilities. This will be a modular system that can adapt to various data requirements.
python
System Architecture
1. Data Generators
MockDataGenerator: Uses Faker to generate synthetic data based on schema
CSVDataGenerator: Transforms existing CSV data
Custom Providers: Extensible with domain-specific data generators
2. Anonymization Methods
Masking: Partial masking (first/last character visible)
Hashing: SHA-256 with salt for consistent anonymization
Tokenization: Replaces values with consistent tokens
Generalization: Aggregates values (e.g., age ranges)
Perturbation: Adds noise to numeric values
Nullification: Removes sensitive data entirely
3. Subset Extraction Strategies
Random Sample: Simple random sampling
Stratified: Proportional sampling across categories
Time-based: Filter by date/time ranges
Conditional: SQL-like query conditions
Percentage: Percentage-based sampling
4. Refresh Cadence
Built-in schedules: Daily, Weekly, Monthly
Custom intervals with timedelta
Once-only generation option
Automatic refresh checking based on last refresh time
This system provides a production-ready foundation that can be extended for specific domain requirements while maintaining data privacy and consistency across refresh cycles.
"""
Test Data Management System (TDMS)
A modular system for generating, anonymizing, subsetting, and managing test data refresh cycles.
"""
import hashlib
import json
import logging
import random
import re
import string
import uuid
from abc import ABC, abstractmethod
from datetime import datetime, timedelta
from enum import Enum
from typing import Any, Callable, Dict, List, Optional, Tuple, Union
import pandas as pd
from faker import Faker
from faker.providers import BaseProvider
# Configure logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
# ==================== ENUMS ====================
class DataFormat(Enum):
CSV = "csv"
JSON = "json"
PARQUET = "parquet"
DATAFRAME = "dataframe"
class RefreshFrequency(Enum):
ONCE = "once"
DAILY = "daily"
WEEKLY = "weekly"
MONTHLY = "monthly"
CUSTOM = "custom"
class AnonymizationMethod(Enum):
MASK = "mask"
HASH = "hash"
NULLIFY = "nullify"
TOKENIZE = "tokenize"
GENERALIZE = "generalize"
PERTURB = "perturb"
CUSTOM = "custom"
class SubsetStrategy(Enum):
RANDOM_SAMPLE = "random_sample"
STRATIFIED = "stratified"
TIME_BASED = "time_based"
CONDITIONAL = "conditional"
PERCENTAGE = "percentage"
# ==================== BASE CLASSES ====================
class DataGenerator(ABC):
"""Abstract base class for data generators"""
def __init__(self, schema: Dict[str, Any], **kwargs):
self.schema = schema
self.faker = Faker()
self.metadata = {
"generated_at": None,
"record_count": 0,
"generator_type": self.__class__.__name__
}
@abstractmethod
def generate(self, count: int) -> pd.DataFrame:
"""Generate test data"""
pass
def get_metadata(self) -> Dict:
"""Get generation metadata"""
return self.metadata.copy()
class Anonymizer(ABC):
"""Abstract base class for anonymizers"""
def __init__(self, config: Dict[str, AnonymizationMethod]):
self.config = config
self.tokens = {} # For tokenization mapping
self.salt = self._generate_salt()
@abstractmethod
def anonymize(self, df: pd.DataFrame, columns: List[str]) -> pd.DataFrame:
"""Anonymize specified columns"""
pass
def _generate_salt(self) -> str:
"""Generate salt for hashing"""
return uuid.uuid4().hex[:16]
def _hash_value(self, value: Any) -> str:
"""Hash a value with salt"""
if pd.isna(value):
return value
return hashlib.sha256(f"{value}{self.salt}".encode()).hexdigest()[:16]
class SubsetExtractor(ABC):
"""Abstract base class for subset extraction"""
@abstractmethod
def extract(
self,
df: pd.DataFrame,
strategy: SubsetStrategy,
**kwargs
) -> pd.DataFrame:
"""Extract subset based on strategy"""
pass
# ==================== GENERATORS ====================
class MockDataGenerator(DataGenerator):
"""Generates mock data using Faker"""
def generate(self, count: int) -> pd.DataFrame:
"""Generate mock data based on schema"""
data = {}
for col, col_type in self.schema.items():
if col_type == "name":
data[col] = [self.faker.name() for _ in range(count)]
elif col_type == "email":
data[col] = [self.faker.email() for _ in range(count)]
elif col_type == "phone":
data[col] = [self.faker.phone_number() for _ in range(count)]
elif col_type == "address":
data[col] = [self.faker.address() for _ in range(count)]
elif col_type == "company":
data[col] = [self.faker.company() for _ in range(count)]
elif col_type == "date":
data[col] = [self.faker.date_between(
start_date='-2y',
end_date='today'
) for _ in range(count)]
elif col_type == "integer":
data[col] = [random.randint(1, 1000) for _ in range(count)]
elif col_type == "float":
data[col] = [round(random.uniform(1.0, 1000.0), 2)
for _ in range(count)]
elif col_type == "boolean":
data[col] = [random.choice([True, False]) for _ in range(count)]
elif col_type == "uuid":
data[col] = [str(uuid.uuid4()) for _ in range(count)]
elif isinstance(col_type, dict) and "choices" in col_type:
data[col] = [random.choice(col_type["choices"])
for _ in range(count)]
else:
# Custom generator
if callable(col_type):
data[col] = [col_type() for _ in range(count)]
else:
data[col] = [col_type for _ in range(count)]
df = pd.DataFrame(data)
self.metadata["generated_at"] = datetime.now().isoformat()
self.metadata["record_count"] = count
return df
class CSVDataGenerator(DataGenerator):
"""Generates data from existing CSV with transformations"""
def __init__(self, source_path: str, transformations: Optional[Dict] = None):
self.source_path = source_path
self.transformations = transformations or {}
super().__init__(schema={})
def generate(self, count: int = None) -> pd.DataFrame:
"""Load and transform existing CSV data"""
df = pd.read_csv(self.source_path)
# Apply transformations
for col, transform in self.transformations.items():
if col in df.columns:
if transform == "uppercase":
df[col] = df[col].str.upper()
elif transform == "lowercase":
df[col] = df[col].str.lower()
elif transform == "trim":
df[col] = df[col].str.strip()
elif isinstance(transform, dict):
# Value mapping
df[col] = df[col].map(transform).fillna(df[col])
# If count specified, sample
if count and count < len(df):
df = df.sample(n=count, random_state=42)
self.metadata["generated_at"] = datetime.now().isoformat()
self.metadata["record_count"] = len(df)
return df
# ==================== ANONYMIZERS ====================
class DefaultAnonymizer(Anonymizer):
"""Default anonymizer with multiple methods"""
def anonymize(self, df: pd.DataFrame, columns: List[str]) -> pd.DataFrame:
"""Anonymize specified columns based on config"""
df_anon = df.copy()
for col in columns:
if col not in df_anon.columns:
logger.warning(f"Column {col} not found in dataframe")
continue
method = self.config.get(col, AnonymizationMethod.MASK)
if method == AnonymizationMethod.MASK:
df_anon[col] = df_anon[col].astype(str).apply(
lambda x: self._mask_value(x)
)
elif method == AnonymizationMethod.HASH:
df_anon[col] = df_anon[col].apply(self._hash_value)
elif method == AnonymizationMethod.NULLIFY:
df_anon[col] = None
elif method == AnonymizationMethod.TOKENIZE:
df_anon[col] = df_anon[col].apply(self._tokenize)
elif method == AnonymizationMethod.GENERALIZE:
df_anon[col] = self._generalize(df_anon[col])
elif method == AnonymizationMethod.PERTURB:
df_anon[col] = self._perturb(df_anon[col])
elif method == AnonymizationMethod.CUSTOM:
# Custom function in config
custom_func = self.config.get(f"{col}_func")
if custom_func:
df_anon[col] = df_anon[col].apply(custom_func)
return df_anon
def _mask_value(self, value: str) -> str:
"""Mask value keeping first and last character"""
if pd.isna(value):
return value
s = str(value)
if len(s) <= 2:
return '*' * len(s)
return s[0] + '*' * (len(s) - 2) + s[-1]
def _tokenize(self, value: Any) -> str:
"""Replace with consistent token"""
str_val = str(value)
if str_val not in self.tokens:
self.tokens[str_val] = f"TOKEN_{len(self.tokens)+1:06d}"
return self.tokens[str_val]
def _generalize(self, series: pd.Series) -> pd.Series:
"""Generalize numeric values to ranges"""
if pd.api.types.is_numeric_dtype(series):
return pd.cut(series, bins=5, labels=False)
return series
def _perturb(self, series: pd.Series) -> pd.Series:
"""Add random noise to numeric values"""
if pd.api.types.is_numeric_dtype(series):
noise = series.std() * 0.1 if series.std() > 0 else 1
return series + pd.Series([random.uniform(-noise, noise)
for _ in range(len(series))])
return series
# ==================== SUBSET EXTRACTORS ====================
class DefaultSubsetExtractor(SubsetExtractor):
"""Default subset extractor with multiple strategies"""
def extract(
self,
df: pd.DataFrame,
strategy: SubsetStrategy,
**kwargs
) -> pd.DataFrame:
"""Extract subset based on strategy"""
if strategy == SubsetStrategy.RANDOM_SAMPLE:
n = kwargs.get('n', 100)
frac = kwargs.get('frac')
return df.sample(n=n, frac=frac, random_state=42)
elif strategy == SubsetStrategy.STRATIFIED:
stratify_col = kwargs.get('stratify_column')
if not stratify_col or stratify_col not in df.columns:
raise ValueError(f"Stratify column '{stratify_col}' not found")
samples = []
for value in df[stratify_col].unique():
subset = df[df[stratify_col] == value]
n_per_stratum = kwargs.get('n_per_stratum', 10)
if len(subset) > n_per_stratum:
subset = subset.sample(n=n_per_stratum, random_state=42)
samples.append(subset)
return pd.concat(samples, ignore_index=True)
elif strategy == SubsetStrategy.TIME_BASED:
time_col = kwargs.get('time_column')
if not time_col or time_col not in df.columns:
raise ValueError(f"Time column '{time_col}' not found")
df[time_col] = pd.to_datetime(df[time_col])
start_date = kwargs.get('start_date',
datetime.now() - timedelta(days=30))
end_date = kwargs.get('end_date', datetime.now())
mask = (df[time_col] >= start_date) & (df[time_col] <= end_date)
return df[mask]
elif strategy == SubsetStrategy.CONDITIONAL:
condition = kwargs.get('condition')
if not condition:
raise ValueError("Condition must be provided")
return df.query(condition)
elif strategy == SubsetStrategy.PERCENTAGE:
frac = kwargs.get('frac', 0.1)
return df.sample(frac=frac, random_state=42)
else:
raise ValueError(f"Unknown strategy: {strategy}")
# ==================== MAIN SYSTEM ====================
class TestDataManager:
"""Main test data management system"""
def __init__(
self,
generator: DataGenerator,
anonymizer: Optional[Anonymizer] = None,
subset_extractor: Optional[SubsetExtractor] = None,
storage_path: Optional[str] = None
):
self.generator = generator
self.anonymizer = anonymizer
self.subset_extractor = subset_extractor or DefaultSubsetExtractor()
self.storage_path = storage_path
self._current_data: Optional[pd.DataFrame] = None
self._refresh_schedule: Optional[Dict] = None
self._last_refresh: Optional[datetime] = None
logger.info("Test Data Manager initialized")
def generate_data(
self,
count: int = 1000,
save: bool = False,
anonymize_columns: Optional[List[str]] = None
) -> pd.DataFrame:
"""Generate new test data"""
logger.info(f"Generating {count} records...")
# Generate raw data
raw_data = self.generator.generate(count)
# Anonymize if requested
if self.anonymizer and anonymize_columns:
logger.info(f"Anonymizing columns: {anonymize_columns}")
raw_data = self.anonymizer.anonymize(raw_data, anonymize_columns)
self._current_data = raw_data
self._last_refresh = datetime.now()
# Save if requested
if save and self.storage_path:
self._save_data(raw_data)
logger.info(f"Generated {len(raw_data)} records")
return raw_data
def get_subset(
self,
strategy: SubsetStrategy = SubsetStrategy.RANDOM_SAMPLE,
**kwargs
) -> pd.DataFrame:
"""Extract subset from current data"""
if self._current_data is None:
self.generate_data()
logger.info(f"Extracting subset using {strategy.value} strategy...")
subset = self.subset_extractor.extract(
self._current_data, strategy, **kwargs
)
logger.info(f"Extracted {len(subset)} records")
return subset
def refresh(
self,
frequency: RefreshFrequency = RefreshFrequency.ONCE,
custom_interval: Optional[timedelta] = None,
count: int = 1000,
**kwargs
) -> pd.DataFrame:
"""Refresh data based on cadence"""
now = datetime.now()
should_refresh = True
# Check if refresh is needed based on frequency
if self._last_refresh and frequency != RefreshFrequency.ONCE:
if frequency == RefreshFrequency.DAILY:
should_refresh = (now - self._last_refresh).days >= 1
elif frequency == RefreshFrequency.WEEKLY:
should_refresh = (now - self._last_refresh).days >= 7
elif frequency == RefreshFrequency.MONTHLY:
should_refresh = (now - self._last_refresh).days >= 30
elif frequency == RefreshFrequency.CUSTOM and custom_interval:
should_refresh = (now - self._last_refresh) >= custom_interval
if should_refresh:
logger.info(f"Refreshing data (frequency: {frequency.value})")
return self.generate_data(count=count, **kwargs)
else:
logger.info("No refresh needed based on schedule")
return self._current_data if self._current_data is not None else self.generate_data(count)
def _save_data(self, df: pd.DataFrame):
"""Save data to storage"""
if not self.storage_path:
return
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
filename = f"{self.storage_path}/test_data_{timestamp}"
if self.storage_path.endswith('.csv'):
df.to_csv(f"{filename}.csv", index=False)
elif self.storage_path.endswith('.json'):
df.to_json(f"{filename}.json", orient='records', indent=2)
elif self.storage_path.endswith('.parquet'):
df.to_parquet(f"{filename}.parquet", index=False)
# Save metadata
metadata = self.get_metadata()
with open(f"{filename}_metadata.json", 'w') as f:
json.dump(metadata, f, indent=2, default=str)
logger.info(f"Data saved to {filename}")
def get_metadata(self) -> Dict:
"""Get complete metadata"""
metadata = {
"generator_metadata": self.generator.get_metadata(),
"last_refresh": self._last_refresh.isoformat() if self._last_refresh else None,
"current_record_count": len(self._current_data) if self._current_data is not None else 0,
"storage_path": self.storage_path
}
return metadata
def export_data(
self,
format: DataFormat = DataFormat.CSV,
path: Optional[str] = None
) -> str:
"""Export current data in specified format"""
if self._current_data is None:
self.generate_data()
export_path = path or f"export_{datetime.now().strftime('%Y%m%d_%H%M%S')}"
if format == DataFormat.CSV:
full_path = f"{export_path}.csv"
self._current_data.to_csv(full_path, index=False)
elif format == DataFormat.JSON:
full_path = f"{export_path}.json"
self._current_data.to_json(full_path, orient='records', indent=2)
elif format == DataFormat.PARQUET:
full_path = f"{export_path}.parquet"
self._current_data.to_parquet(full_path, index=False)
elif format == DataFormat.DATAFRAME:
return self._current_data
logger.info(f"Data exported to {full_path}")
return full_path
# ==================== FACTORY ====================
class TestDataManagerFactory:
"""Factory for creating configured TestDataManager instances"""
@staticmethod
def create_pii_anonymized_set(
count: int = 1000,
storage_path: str = "./test_data"
) -> TestDataManager:
"""Create a manager with PII anonymization configuration"""
# Schema with PII fields
schema = {
"user_id": "uuid",
"full_name": "name",
"email": "email",
"phone": "phone",
"address": "address",
"ssn": "ssn",
"credit_card": "credit_card_number",
"birth_date": "date_of_birth",
"income": "integer",
"account_balance": "float"
}
generator = MockDataGenerator(schema)
# Anonymization config for PII fields
anonymizer = DefaultAnonymizer({
"full_name": AnonymizationMethod.MASK,
"email": AnonymizationMethod.MASK,
"phone": AnonymizationMethod.MASK,
"address": AnonymizationMethod.MASK,
"ssn": AnonymizationMethod.HASH,
"credit_card": AnonymizationMethod.TOKENIZE,
"birth_date": AnonymizationMethod.GENERALIZE,
"user_id": AnonymizationMethod.HASH
})
return TestDataManager(
generator=generator,
anonymizer=anonymizer,
storage_path=storage_path
)
@staticmethod
def create_sales_data_set(
count: int = 5000,
include_customers: bool = True
) -> TestDataManager:
"""Create a sales dataset"""
schema = {
"order_id": "uuid",
"customer_id": "integer",
"product_name": "company",
"category": lambda: random.choice(["Electronics", "Clothing", "Food", "Books"]),
"quantity": lambda: random.randint(1, 10),
"unit_price": lambda: round(random.uniform(10.0, 1000.0), 2),
"order_date": "date",
"region": lambda: random.choice(["North", "South", "East", "West"])
}
if include_customers:
schema.update({
"customer_name": "name",
"customer_email": "email"
})
generator = MockDataGenerator(schema)
return TestDataManager(
generator=generator,
storage_path="./sales_data"
)
# ==================== EXAMPLE USAGE ====================
def example_usage():
"""Demonstrate system usage"""
# 1. Create a basic test data manager
print("=== Example 1: Basic Usage ===")
schema = {
"id": "uuid",
"name": "name",
"email": "email",
"age": "integer",
"score": "float"
}
generator = MockDataGenerator(schema)
manager = TestDataManager(generator)
# Generate data
data = manager.generate_data(count=100)
print(f"Generated {len(data)} records")
print(data.head())
# Get subset
subset = manager.get_subset(
strategy=SubsetStrategy.CONDITIONAL,
condition="age > 25 and score > 50"
)
print(f"\nSubset: {len(subset)} records")
# 2. Create PII-anonymized dataset
print("\n=== Example 2: PII Anonymization ===")
pii_manager = TestDataManagerFactory.create_pii_anonymized_set(count=50)
# Generate with anonymization
pii_data = pii_manager.generate_data(
count=50,
anonymize_columns=["full_name", "email", "phone", "ssn", "credit_card"]
)
print("PII Data Sample:")
print(pii_data[["full_name", "email", "ssn", "credit_card"]].head())
# 3. Refresh with schedule
print("\n=== Example 3: Scheduled Refresh ===")
sales_manager = TestDataManagerFactory.create_sales_data_set()
# Daily refresh simulation
sales_data = sales_manager.refresh(
frequency=RefreshFrequency.DAILY,
count=1000
)
print(f"Sales data: {len(sales_data)} records")
# Stratified subset
stratified = sales_manager.get_subset(
strategy=SubsetStrategy.STRATIFIED,
stratify_column="category",
n_per_stratum=5
)
print(f"Stratified sample: {len(stratified)} records across categories")
# 4. Export in different formats
print("\n=== Example 4: Export ===")
csv_path = manager.export_data(format=DataFormat.CSV)
print(f"Exported to: {csv_path}")
# 5. Get metadata
print("\n=== Example 5: Metadata ===")
metadata = manager.get_metadata()
print(json.dumps(metadata, indent=2, default=str))
# ==================== CUSTOM PROVIDER ====================
class CustomProvider(BaseProvider):
"""Custom Faker provider for domain-specific data"""
def product_sku(self) -> str:
"""Generate product SKU"""
prefix = random.choice(['EL', 'CL', 'FD', 'BK'])
number = f"{random.randint(1000, 9999)}"
return f"{prefix}-{number}"
def loyalty_tier(self) -> str:
"""Generate loyalty tier"""
return random.choice(['Bronze', 'Silver', 'Gold', 'Platinum'])
def discount_code(self) -> str:
"""Generate discount code"""
chars = string.ascii_uppercase + string.digits
return ''.join(random.choices(chars, k=8))
# ==================== RUN ====================
if __name__ == "__main__":
# Add custom provider to Faker
Faker.add_provider(CustomProvider)
# Run example
example_usage()
print("\n=== System Ready ===")
print("Key Features:")
print("1. Data Generators: Mock, CSV-based, custom providers")
print("2. Anonymization: Mask, Hash, Tokenize, Generalize, Perturb")
print("3. Subsets: Random, Stratified, Time-based, Conditional, Percentage")
print("4. Refresh Cadence: Daily, Weekly, Monthly, Custom intervals")
print("5. Storage: CSV, JSON, Parquet formats")
print("6. Metadata tracking for all operations")