CodingUnit TestsIntermediate30 minSaves 30 minutes

Property-Based Unit Tests for Pricing Functions

Engineers can generate comprehensive property-based test suites for critical pricing functions, ensuring invariants hold and edge cases are covered with shrinking on failure.

Produce a comprehensive property-based unit test suite for a given pricing function. This covers framework setup, test files, fixtures, coverage notes, and CI integration. The tests harden pure logic modules by validating invariants and shrinking failure examples to detect errors.

READY-TO-USE PROMPT

Copy Prompt

prompt.txt
Role: You are an experienced Test Engineer specializing in property-based testing.

Context: I am developing a pure pricing function, `calculate_price(item_id, quantity, user_segment)`, which takes an item identifier, a quantity, and a user segment, returning a final price. This function must adhere to several invariants, such as prices always being non-negative and discounts never resulting in a price lower than a predefined minimum. I need to ensure its reliability with property-based tests.

Task: Generate a complete property-based unit test suite for this pricing function. The suite should use either `Fast-check` (TypeScript/JavaScript) or `Hypothesis` (Python), based on the specified language. Include setup for the chosen framework, concrete examples of property definitions, strategies for generating inputs, and how to handle invariants. Demonstrate shrinking on failure. Provide guidance on integrating these tests into a CI/CD pipeline and considerations for measuring test coverage.

Constraints:
- Target language for the test suite: `{{language}}` (e.g., Python, TypeScript).
- Name of the pricing function: `{{pricing_function_name}}`.
- Signature of the pricing function: `{{pricing_function_signature}}`.
- Key invariants to test (e.g., 'price >= 0', 'discounted price >= min_price'): `{{invariants_list}}`.
- Assume the pricing function is a pure function with no external side effects.
- Tests should focus on properties derived from the function's specification, not just example-based tests.
- Include at least three distinct properties to test.
- Demonstrate how to set up custom arbitraries/strategies if the default ones are insufficient for `item_id` or `user_segment`.

Output:
- Chosen framework setup (e.g., `package.json` scripts, `pyproject.toml` entries).
- Complete test file(s) demonstrating property definitions, input generation, and invariant checks.
- Mocks or fixtures required for any external dependencies, if applicable (though for pure functions, this should be minimal).
- Detailed notes on integrating these tests into a typical CI pipeline (e.g., GitHub Actions, GitLab CI).
- Recommendations for measuring and reporting coverage specifically for property-based tests.

Estimated results

DifficultyIntermediate
Setup time30 min
Time saved30 minutes
Best modelsClaude, ChatGPT, Gemini
Best audienceSoftware Development, Fintech

Editor's note

Why this prompt matters

Testing critical pure logic, like pricing functions, often reveals the limitations of traditional example-based unit tests. While useful for known scenarios, they frequently miss subtle edge cases or violations of fundamental business invariants. A pricing function, for instance, must always return a non-negative value, or a discount should never drop below a defined floor, regardless of input combinations. Manually crafting test cases to cover every permutation quickly becomes impractical and incomplete.

This workflow addresses that challenge directly by applying property-based testing. It moves beyond specific input-output pairs to verify the *properties* that your function should uphold across a broad range of generated inputs. This approach is invaluable for engineers responsible for hardening pure logic modules, especially where financial calculations or complex business rules dictate behavior. By defining what *must always be true* about your function's output, you can systematically uncover bugs that standard tests would overlook.

Implementing property-based tests ensures a higher degree of confidence in the correctness of your core logic. It provides a deterministic way to validate invariants, identify unexpected interactions, and even demonstrate how test failures can be minimized to their simplest form for easier debugging. This is a practical step towards building more resilient and reliable software components.

Anatomy

Prompt engineering breakdown

Role

The model is instructed to act as an experienced Test Engineer specializing in property-based testing.

Context

The user is developing a pure pricing function (`calculate_price`) with specific invariants (non-negative price, minimum discounted price) that requires robust property-based testing for reliability.

Goal

The primary goal is to generate a complete property-based unit test suite for the specified pricing function, including framework setup, property definitions, input strategies, invariant handling, failure shrinking demonstration, CI/CD integration, and coverage notes.

Constraints

Key constraints include specifying the target language, pricing function name and signature, a list of invariants, assuming a pure function, focusing on property-derived tests, requiring at least three distinct properties, and demonstrating custom arbitrary/strategy setup.

Output format

The output must be structured, including the chosen framework setup, complete test file(s), any required mocks/fixtures, detailed CI integration notes, and recommendations for coverage reporting specific to property-based tests.

Why this structure works

This prompt's structure ensures a highly relevant and actionable output. Role priming establishes the correct expert persona, while explicit constraints on language, function details, and invariants guide the model to produce technically precise code. The structured output format guarantees all critical components of a comprehensive test suite are delivered, from setup to CI integration.

Pick your version

Prompt variations

BeginnerWorks with any model

When new to property-based testing or needing a basic setup for a simple function, focusing on core concepts without extensive CI/CD or advanced strategies.

prompt.txt
As a Test Engineer, help me create property-based unit tests for my `{{pricing_function_name}}` function, written in `{{language}}`. This function takes `{{pricing_function_signature}}` and calculates a price. I need to ensure the price is always `{{basic_invariant}}`. Generate a basic property-based test file using either Fast-check or Hypothesis. Include framework setup, one clear property definition, and simple input generation strategies. Briefly explain how to execute these tests and what happens if a test fails, demonstrating the concept of shrinking.
ProfessionalBest with claude

When a thorough, production-ready property-based test suite is required for a complex pricing function, covering all specified details, CI integration, and advanced input strategies.

prompt.txt
Role: You are an experienced Test Engineer specializing in property-based testing.
Context: I am developing a pure pricing function, `{{pricing_function_name}}`, with the signature `{{pricing_function_signature}}`. It must adhere to invariants like 'price is always non-negative' and 'discounts never result in a price lower than a predefined minimum'. I need robust property-based tests.
Task: Generate a complete property-based unit test suite for this function using `{{language}}`. Include framework setup, concrete examples of property definitions, input generation strategies (including custom arbitraries for `{{custom_arbitrary_fields}}`), and handling of `{{invariants_list}}`. Demonstrate shrinking.
Constraints: Focus on properties derived from the specification. Include at least three distinct properties.
Output: Framework setup, complete test file(s), notes on CI integration, and recommendations for coverage reporting.
Short VersionBest with chatgpt

For quick prototypes or when only the core property-based test generation is needed without extensive setup or CI details, focusing purely on the test logic.

prompt.txt
Generate property-based unit tests for my `{{pricing_function_name}}` function in `{{language}}`, which has the signature `{{pricing_function_signature}}`. The function must uphold invariants like `{{invariants_list}}`. Use either Fast-check or Hypothesis to define at least two properties, generate inputs, and show how to check these invariants. Focus on the core test logic, including an example of shrinking on failure. Provide the main test file and minimal setup instructions.
EnterpriseBest with gemini

For critical financial systems where regulatory compliance, auditability, and extreme reliability of pricing logic are paramount, requiring detailed risk mitigation and stakeholder reporting.

prompt.txt
Role: You are a Lead Test Architect with a focus on financial system reliability and compliance.
Context: Our organization requires property-based testing for a critical `{{pricing_function_name}}` function, `{{pricing_function_signature}}`, which calculates prices for high-volume transactions. This function's integrity is vital for regulatory compliance and financial accuracy. Key invariants include `{{invariants_list}}`. We need to demonstrate extreme reliability and auditability.
Task: Design a comprehensive property-based test suite using `{{language}}` (Fast-check or Hypothesis). Include advanced strategies for input generation (e.g., custom arbitraries for sensitive data types like `{{item_id_type}}` or `{{user_segment_type}}`), detailed property definitions covering all business rules and edge cases, and robust invariant checking.
Constraints: Tests must provide clear audit trails for failures and shrinking behavior. Emphasize coverage and explain how these tests mitigate financial risk.
Output: Full test suite, CI integration with compliance logging, and a strategy for demonstrating test effectiveness to stakeholders.

What you'll get

Expected output

The output will provide a complete property-based unit test suite, typically implemented in Python using Hypothesis or TypeScript with Fast-check, depending on the specified language. It focuses on ensuring the {{pricing_function_name}} function adheres to its invariants.

First, the output details the Chosen Framework Setup. For Python, this includes a pyproject.toml snippet adding hypothesis and pytest to development dependencies, along with a pytest.ini for basic configuration. If TypeScript is selected, a package.json entry for fast-check and jest (or a similar test runner) will be provided, including relevant tsconfig.json adjustments.

Following this, a Complete Test File named test_{{pricing_function_name}}.py (or .ts) will be presented. This file demonstrates:

  • Custom Strategies/Arbitraries: Specific examples for generating inputs for item_id and user_segment. For item_id, this might be a strategy for valid UUIDs or a fixed set of known item codes. For user_segment, an arbitrary generating strings like 'guest', 'standard', 'premium' is included, ensuring realistic inputs.
  • Property Definitions: At least three distinct properties are implemented. For instance:

* test_price_is_non_negative: Asserts that calculate_price always returns a value greater than or equal to zero. * test_discounted_price_not_below_minimum: Verifies that, even with various discounts, the final price never falls below a predefined floor price, addressing {{invariants_list}} like 'discounted price >= min_price'. * test_price_monotonicity_with_quantity: Checks that for a fixed item and user segment, increasing the quantity either maintains or increases the total price, ensuring expected economic behavior.

  • Invariant Handling: The tests will show how to use assume (Hypothesis) or fc.pre (Fast-check) to filter out generated inputs that do not meet the preconditions for a specific property, ensuring tests only run on relevant data subsets.
  • Shrinking on Failure: While not explicitly a separate section, the provided test structure implicitly demonstrates shrinking. If a property fails, the framework will automatically simplify the failing input to the smallest possible example, aiding in rapid debugging.

Given that {{pricing_function_name}} is a pure function, Mocks or Fixtures are minimal. The output might include simple data structures or helper functions to represent valid input ranges for item_id or user_segment if they were to originate from a predefined data source.

The CI Pipeline Integration notes provide detailed guidance for platforms like GitHub Actions or GitLab CI. This covers environment setup, dependency installation commands (pip install, npm ci), and running the test suite (pytest, jest). It also explains how to interpret test results, particularly the output from Hypothesis or Fast-check during failures.

Finally, Recommendations for Measuring Coverage are included. The output clarifies that while traditional line/branch coverage tools (pytest-cov, nyc) can be used, property-based tests primarily aim for *state space* coverage. It advises complementing property tests with targeted example-based tests for known edge cases and considering mutation testing to assess the robustness of the defined properties.

Under the hood

Why this prompt works

The prompt's efficacy stems from its structured approach to a complex task. By establishing a clear Role as a "Test Engineer specializing in property-based testing," the model adopts the necessary expertise and perspective for generating practical, reliable tests. The Context provides a precise function signature and domain, anchoring the response to a realistic scenario and avoiding generic abstractions.

Explicitly naming frameworks like Fast-check or Hypothesis ensures the generated code is immediately actionable and aligns with industry standards. The detailed Task outlines the required components: setup, property definitions, input strategies, invariant handling, and crucial demonstration of shrinking on failure. This comprehensive scope guides the model to produce a complete, rather than partial, solution.

The prompt effectively uses Constraints to enforce quality and depth. Requiring "at least three distinct properties" and "custom arbitraries/strategies" pushes beyond basic examples, ensuring robust test cases. Furthermore, the templated Constraints for language, function name, and invariants ({{language}}, {{invariants_list}}) enable high reusability and targeted generation. Finally, the explicit Output structure dictates specific deliverables, from test files to CI/CD integration and coverage recommendations, ensuring a holistic and immediately useful suite of advice and code.

Model fit

Best AI models for this prompt

Claude

Claude performs well in reasoning about test structure and providing detailed explanations for property definitions and invariant handling. It can generate boilerplate and property ideas effectively, though explicit guidance on specific framework syntax (Fast-check or Hypothesis) might be needed for optimal results. See the full Claude hub for deeper guidance.

ChatGPT

ChatGPT is strong at generating functional code and common testing patterns. It adapts well to specific library syntax for Fast-check or Hypothesis, producing concrete property definitions and input strategies. Always verify the generated properties against your exact requirements. See the full ChatGPT hub for deeper guidance.

Gemini

Gemini is capable of producing comprehensive code for test logic and setup, making it suitable for generating diverse input strategies for property-based tests. Ensure its explanations for test integration and coverage align with established best practices in your development workflow. See the full Gemini hub for deeper guidance.

When to use

  • Validating complex pricing logic with multiple variables (e.g., quantity, segment, promotions).
  • Hardening pure functions where many input combinations could lead to subtle bugs.
  • Ensuring pricing invariants (e.g., price always non-negative, discounts within limits) hold across diverse inputs.
  • Confirming refactored pricing algorithms maintain previous behavior without regression.
  • Exploring edge cases and boundary conditions that might be missed by example-based tests.

When not to use

  • Testing simple data transformations or getter/setter functions where properties are trivial.
  • Verifying UI interactions or end-to-end workflows that involve external systems or user interfaces.
  • Initial stages of development when the function's behavior and invariants are still undefined.
  • Testing functions with significant side effects or non-deterministic outputs that cannot be easily isolated.
  • When the cost of defining properties and custom strategies outweighs the benefit for a low-risk, stable function.

Get more from it

Pro tips

  • 1

    Start with basic invariants like non-negative prices; build complexity incrementally to avoid overwhelming the property definition process.

  • 2

    Define custom arbitraries for domain-specific inputs such as `item_id` or `user_segment` to generate relevant and realistic test data.

  • 3

    Validate the shrinking behavior on test failures; a well-shrunk counterexample drastically reduces debugging time.

  • 4

    Ensure your pricing function is truly pure. Property-based testing works best when there are no external side effects or hidden state.

  • 5

    Combine properties where appropriate, but prefer atomic, single-concern properties for clarity and easier debugging.

  • 6

    Integrate property-based tests into your CI pipeline early to catch regressions before they reach production.

Don't ship this

Common mistakes

  • Defining properties that are too broad or too vague, leading to false positives or meaningless tests.

    Fix — Focus on specific invariants or behavioral rules. Break down complex properties into smaller, more focused assertions.

  • Using default data generation strategies for complex inputs, resulting in unrealistic or insufficient test coverage.

    Fix — Implement custom arbitraries or strategies to generate inputs that reflect your application's specific data constraints and distributions.

  • Ignoring the shrinking output when a test fails, missing the opportunity to quickly identify the minimal failing input.

    Fix — Always examine the shrunk counterexample provided by the framework; it's designed to simplify debugging and pinpoint the root cause.

  • Attempting to property-test functions with unmocked external dependencies or side effects, leading to flaky tests.

    Fix — Isolate the pure pricing logic. Mock any external calls (e.g., database lookups, API calls) to ensure deterministic test execution.

  • Not explicitly defining the range or characteristics of generated numbers (e.g., quantity must be positive integers).

    Fix — Specify precise constraints on generated data within your arbitraries, ensuring they align with valid inputs for your pricing function.

  • Focusing solely on 'happy path' properties and neglecting edge cases or boundary conditions.

    Fix — Actively brainstorm potential edge cases for your pricing function and design properties or adjust arbitraries to cover them.

People also ask

Frequently asked questions

Q.Can I use this approach for functions that are not strictly pure, like those with database lookups?

Property-based testing is most effective for pure functions. If your function has dependencies, mock them to isolate the pure computational logic. This allows you to test the core pricing algorithm deterministically.

Q.How do I handle floating-point comparisons when testing prices?

Avoid direct equality comparisons with floats. Instead, assert that the absolute difference between two floating-point numbers is less than a small epsilon value. This accounts for precision issues inherent in floating-point arithmetic.

Q.What if my pricing function has many input parameters? Does this scale?

Yes, it scales. You'll define arbitraries for each parameter. The key is to design properties that test interactions between a subset of parameters or specific invariants, rather than trying to test every permutation simultaneously in one property.

Q.How many properties should I aim for in a test suite?

The number is less important than the coverage of your business rules and invariants. Aim for distinct properties that cover all critical aspects of your pricing logic, including edge cases and error conditions. Three to five solid properties often suffice for a single function.

Q.Is property-based testing a replacement for example-based unit tests?

No, it's complementary. Example-based tests are good for documenting specific scenarios or known bugs. Property-based tests excel at exploring the input space and finding unforeseen issues by generating many diverse inputs.

Q.How do I ensure my generated inputs are realistic for `item_id` or `user_segment`?

Use custom arbitraries that draw from a defined set of valid item_ids or user_segments, or generate values that adhere to their expected format and range. This makes tests more relevant to your domain.

Version 1.0Last reviewed July 20, 2026
Reviewed by PromptInFlow Editorial Team