All notes

Property-Based Tests Begin with Business Invariants

Generate and shrink inputs only after defining independent properties worth defending.

English edition, edited for length. Read the complete Chinese original.

If you divide $100 equally among three people, the result should be $33.33 each, not three people with $33 each. Several examples can illustrate this problem, but it’s easy to miss negative numbers, zero values, and very large amounts. The property test was changed to a different problem: regardless of the valid input, the total sum must equal the original amount.

This doesn’t mean randomly generating a bunch of values and then confirming that the function doesn’t throw an error. The first step is to identify the business requirements, and then generate inputs that meet those requirements. If the requirements are incorrect, the tool will simply continue to highlight the flawed design.

Extracting Properties from Business Definitions

Taking the example of dividing an amount into integer values, at least three properties should be ensured:

  1. The sum of all shares equals the total amount.
  2. The difference between any two shares does not exceed the smallest unit.
  3. The number of output shares equals the number of people.

If only non-negative amounts are allowed, it should be explicitly rejected to input negative numbers, rather than allowing the generator to secretly avoid them.

fc.assert(fc.property(
  fc.integer({ min: 0, max: 1_000_000 }),
  fc.integer({ min: 1, max: 100 }),
  (total, people) => {
    const parts = split(total, people);
    return parts.length === people &&
      parts.reduce((sum, x) => sum + x, 0) === total;
  }
));

This example demonstrates one property; the remaining properties should be documented separately for easier troubleshooting. The maximum amount and maximum number of users are test assumptions, not production capacity guarantees. If production uses larger integers or BigInts, you need to match the actual range of values.

Example Scenario: Assume the total amount is non-negative and the number of people is at least one. The prerequisite for entering the production input contract is that the values are valid. If the values are zero, negative, non-integer, or exceed the specified range, a rejection mechanism should be implemented to prevent incorrect results. The generator should not only avoid invalid values but also explicitly state that the function handles all valid inputs. Note that TypeScript numbers can include NaN and infinity, and runtime validation and compile-time type checking are not guarantees that they are the same.

The fc value in the example comes from fast-check, and split represents a sample function. In a real project, the functions are imported and used according to the chosen testing framework. When selecting the range of numbers, it’s important to ensure that the sum does not exceed the maximum safe integer. For the BigInt business, a corresponding generator is used. In addition to the total sum, the fair distribution also considers the number of shares and the maximum difference. If necessary, it also specifies which number receives the remainder. Whether the order of input affects the distribution is a business decision, and it should be explicitly defined rather than left to chance by the algorithm.

Separate assertions with different properties can indicate whether the error is due to a sum error or an error in fairness. A function that always returns zero might satisfy the non-negativity constraint, but not the conservation constraint; a function that always assigns the total amount to the first person satisfies the sum constraint, but not the fairness constraint. The cross-property constraints are not meaningful because they cannot be used to select only the most easily satisfied relationship.

Don’t use the same algorithm to validate yourself

The implementation being tested uses the division and remainder allocation method. The test then replicates the same division and remainder logic to generate the expected array. This means that the same error could potentially occur in both places. Ideally, the properties should be derived from the relationship between the results, rather than by repeating the steps.

Reference models can also be valuable, but they should be simpler and easier to review. For example, comparing a simple, but slow, exhaustive algorithm used on a small scale with a high-performance implementation. The size of the test data is controlled, and the reference model does not need to handle production throughput tasks.

The same applies to serialization and deserialization. decode(encode(x)) = x represents a valid property, but if both encoding and decoding lose a particular field, the test might still pass, depending on whether the comparison object and the input generator cover that field. There should be cross-constraints between the properties.

When the sorted output cannot be pre-listed, it is possible to verify that the results are ordered, that the set of elements remains consistent, and that re-sorting the results yields the same output. Each relationship describes different attributes, and the individual idempotency cannot prove the correctness of the sorting because the original output is also idempotent. Pagination can verify that the input is stable and that consecutive traversal without repetition or omission is maintained, and that the agreed-upon behavior after a valid insertion is also preserved. By crossing reference models and relationship assertions, the implementation is more independent than simply copying and producing.

Data compression can verify decoding round-trip times, but it still needs to be compared against external standards to avoid using non-standard formats for both encoding and decoding. Serialization can verify that key fields are preserved and check for default and unknown field policies. The round-trip relationship is strong but limited, and the range and method of comparison determine whether it can detect missing data. Each property specifies what it proves and what it does not prove.

When the external network or real-time conditions make the results uncertain, first perform pure logical extraction or dependency injection, and then choose an appropriate level of integration test coverage. Property testing does not require running the entire system thousands of times randomly to be valuable. Run budgets, seeds, and version records allow CI failures to be reproducible; real concurrency and database semantics are validated by the corresponding integration layer.

The Generator Defines the World You See

If the generator only produces ASCII names, it won’t be able to detect issues with Chinese characters, combined characters, or whitespace handling. If the generator only produces a list of non-repeating values, it won’t be able to identify the boundaries of deduplication and sorting. The generator should deliberately handle legitimate but difficult-to-handle inputs, rather than simply generating aesthetically pleasing, common values.

It’s generally better to construct valid objects rather than generating a large number and then filtering them. Excessive filtering can reduce the number of effective samples and also make the testing runtime unpredictable. When dealing with data that has associated constraints, such as account status, constructing objects based on the status is more clear and concise than concatenating individual fields.

Invalid inputs should have a distinct nature, with clear and unambiguous rejection and no side effects. Do not mix successful and error paths within the same assertion, so that all failures become “potentially valid exceptions.”

Generating random integers uniformly may rarely encounter zeros, upper bounds, and exactly divisible boundaries. By mixing special values with general values, we can observe branch coverage and effective samples. Identifiers, records at the same time, empty arrays, and long strings should have realistic probabilities, and not just exist in theoretical ranges. Increasing the sample size cannot compensate for models that rarely generate key patterns.

The generator is constructed with legal constraints, such as the end time not being earlier than the start time, and the number of orders corresponding to the number of items. Filtering out a large number of illegal combinations would waste samples and could make the test appear to run for a long time while only checking a small number of cases. Specifically generated and validated invalid inputs fall into the category of “rejection” and have no side effects or error categories. Once the semantic constraints are clear, the reduction can retain the valid preconditions.

Unicode testing can cover combinations of characters, simplified/traditional Chinese, whitespace, and different encoding formats. However, whether the input is normalized is determined by the product itself. It is not possible to require that all names be converted to lowercase and remain the same. If the business requires case-sensitive distinctions, this is an incorrect assumption. Before the tool searches for counterexamples, the team must first confirm that the rules are actually valid. The property is not a coincidence derived from the current function’s behavior.

Making counterexamples readable

After a failure, the property testing framework attempts to reduce the input, finding a simpler counterexample. A failure array containing hundreds of elements may eventually be reduced to two identical identifiers. This process is more intuitive than simply recording random seeds, making it easier to understand the root cause.

The failed test seeds, along with the reduced input, allow for continuous integration to re-run the tests. After fixing the issue, the minimal failing case is converted into a standard regression test, preventing future generators from losing the protection if they change. The property tests are responsible for finding unknown boundaries, while the example tests are responsible for solidifying known lessons learned. These two types of tests do not need to be mutually exclusive.

If a test fails and cannot be re-run, first check if the function being tested relies on time, random numbers, external services, or shared state. Explicitly inject these dependencies to ensure that the input truly controls the result. This often also improves the structure of the production code.

After fixing, the minimum input and any violations of the invariants are preserved, not just the random seed. Upgrading the framework or generator may cause the same seed to produce different inputs, making explicit examples more stable. Using the seed and execution path helps reproduce the original findings, while regular regression examples fix known issues. Together, these approaches prevent property testing from becoming occasional, unexplained failures.

When a review fails, first determine which aspect – the nature, preconditions, generator, or implementation – is incorrect. Do not eliminate counter-examples solely to narrow the scope and allow the process to proceed. All inputs identified by the tool do not necessarily need to support the contract. When updating a contract, record the changes to the legal boundaries. The authority for testing comes from real-world constraints, not from apparent randomness, which can make things seem complex.

State machines can verify action sequences

The addition, deletion, and modification of items in the shopping cart, as well as individual operations, are functioning correctly. However, when combining multiple operations, the total price may be incorrect. The state machine testing generates action sequences, which are then compared to the expected state tracked by a simple model, and the actual system.

The model should maintain business invariants, such as the quantity being non-negative, deleting non-existent items not creating new items, and the total price being zero after clearing. The preconditions for actions should also be included in the model, otherwise the tool may construct paths that are fundamentally disallowed by the business.

The sequence length must be controlled. Repeatedly performing a slow database operation thousands of times is very expensive. Instead, a pure state machine can be placed in memory, and the persistence boundary can be verified using a smaller, integrated scenario. The test scope must be explainable; it’s not about generating the most number of tests, but about ensuring their reliability.

Does the “remove from cart” function only apply to existing items, or does it also allow the deletion of non-existent items as a no-op? What happens when adding zero quantity is attempted? These rules are initially defined in the model, and the tool then generates the corresponding actions. If the model unconditionally accepts all operations, it could potentially lead to testing scenarios that will never be reached. If the model replicates a real implementation, errors will also be inherited. By using a simple business model and observable results, we avoid rebuilding a second, equally complex system.

The task state machine can generate states for “received,” “heartbeat,” “expired,” “cancelled,” and “completed,” but requires persistent storage integration for real lease concurrency. The pure model checking approach ensures legal migration, while integration testing checks for atomic competition between two layers. Each sequence record contains a seed and the minimum actions, and failure cases are often a few key steps in a specific order, which is more effective than random searching for a long time. The maximum number of actions is determined by the running cost to prevent CI from endlessly searching.

To deliberately introduce a few easily verifiable error detection capabilities in sorting, partitioning, or normalization functions. Removing remainders, dropping fields, swapping the order of equal values – these operations should fail and provide meaningful counterexamples. Mutation testing can systematically check, but it cannot prove complete correctness; some mutations that don’t kill the function may be equivalent. The ability to detect errors is more closely related to the quality of the function than the number of times it has been run.

Generator Statistics Help: Verify coverage for specific categories. Report the frequency of zero values, boundary values, duplicates, and empty sets. Do not treat ten thousand common values as ten thousand different risks. Maintain the legal basis for the production range, and adjust the generator and integer model when the capacity changes. Evolve alongside the nature and business agreements, to avoid having rules that are still deemed inapplicable after many years.

The final document uses natural language to explain the invariants and preconditions, and the code implementation allows for executable verification. Readers can independently determine whether the conservation, fairness, and rejection rules are reasonable, without needing to first understand the framework’s syntax. The tool is simply a searcher; the real outcome is for the team to clearly identify which facts must hold true under all allowed inputs.

Testing Independence Using Three Error Propagation Measures

Achieving “A” always returns zero, satisfying non-negativity but violating conservation; achieving “B” gives the entire amount to the first person, satisfying conservation and quantity but violating fairness; achieving “C” discards the remainder, which may pass on many divisibility samples but fails in the overall sum. These variations can be treated as controlled experiments to observe whether the combination of properties can reject them. Individual relationships are often insufficient to define the business, and cross-constraints help identify seemingly reasonable but meaningless implementations.

Fairness also needs to be defined in terms of how the remainder is allocated. Whether the first few inputs conform to the product rules and whether rotation is needed is determined by the business, not the testing framework. If the input order should not affect the long-term allocation for each person, a different rotation model can be used, but it cannot arbitrarily require that each allocation be exactly the same. The system must respond to genuine commitments, and the tool will not judge whether a particular allocation is “fair” for the business.

When using safe integers or BigInt for the amount, the generator and the summation function use the same representation range. NaN, infinity, non-integer, and non-legal numbers are individually validated and rejected; they are not allowed to be included in the successful generator output, and any exceptions can be thrown. The rejection mechanism should also avoid partial outputs or external side effects, and the input boundary and calculation layer can be tested separately. The TypeScript number type cannot express all these runtime constraints.

Generator Distribution Determines the Frequency of Key Morphologies

The legal range, including zero, does not imply that zero will frequently appear. The list allows for repetition, but this does not mean that uniformly generated identifiers will necessarily repeat. By explicitly mixing special values and ordinary values, we can analyze the frequency of zeros, upper bounds, integer divisions, remainders, and repetitions. A large sample size consisting entirely of ordinary values can be wasteful in terms of computational resources. When assessing risk, it is important to consider that a seemingly random distribution does not necessarily guarantee complete coverage.

Related objects must be constructed in a valid state, with necessary preconditions such as start and end times, the number of order items, and permission combinations. A large number of filters can result in a small number of valid samples and a loss of clear explanation. There is also an illegal input generator that precisely classifies expected errors rather than catching any exceptions. This failure can pinpoint the contract, the preconditions, or the implementation, rather than becoming a tool that constantly reports incomprehensible input.

Unicode normalization offers business choices. Combining characters with different forms may require equivalence, product encoding case sensitivity may need to be distinguished, and not all text has the same properties. The generator covers the actual supported character sets, whitespace, and boundary lengths, while preserving product-specific rejection rules. The breadth of testing comes from a comprehensive set of valid risks, not from a slogan that allows any character.

Why Might a Round-Trip Operation Potentially Lose Fields?

The encoder ignores the updatedAt field, and the decoder does not generate it. If the comparison only checks the id and title fields, the bidirectional relationship is still maintained. The input object must cover important fields and, optionally, include independent standard samples or external implementation checks. The bidirectional proof demonstrates the relationship between the two functions, but it does not automatically prove that they comply with external protocols. When comparing structures and omitting fields, it is important to explain why that field does not carry any semantic meaning.

The sorting test also requires that the input set maintains order, has multiple elements, and preserves the identity relationship. If the identity relationship is preserved but the sorting is not, or if the sorting is performed but duplicates are lost, the performance will be slower. This approach is suitable for small, independent, and easily verifiable datasets, and does not involve copying or generating algorithms. Combining this approach with the simple model leads to a contradiction, but it cannot be claimed that all possible inputs have been exhausted unless the actual range and verification methods support this conclusion.

Minimal Input After Contraction Leads to Long-Term Regression

Failed seeds and execution paths help reproduce the current framework version, and explicit minimal inputs allow lessons learned to be preserved across upgrades. After fixing, convert to a standard example, retaining the violation’s invariant explanation. The generator will be adjusted to prevent known counterexamples from disappearing. Do not remove counterexamples to narrow the scope of “green lights”; first, determine if they belong to a valid contract. When the contract actually changes, record the reason and the impact on the consumer.

Before failure, first check the time, random source, shared state, and network to ensure they are truly under control. A fake clock is suitable for local time-based logic, while real-time cancellation requires an integration layer. Test the input control results clearly, and ensure that the behavior remains consistent across multiple runs. Logs should not print sensitive random data; the synthesized state is sufficient to verify the model.

Action Sequence Models Cannot Be a Second Complex Implementation

The shopping cart model only stores items and quantities, defining the legitimate rules for adding, modifying, deleting, and clearing. It then compares the total amount and member information. The implementation uses caching or indexing, and the model does not optimize these. Restrictions such as unauthorized operations and invalid quantities are enforced, and individual validation of sequences is rejected. A model as complex as the production implementation is prone to inheriting errors and significantly increases maintenance costs.

The background task model can generate states for “received,” “expired,” “cancelled,” and “completed,” and verify the valid final state. Real multi-executor atomicity is achieved using a database and controlled synchronization points to prove it. Pure action models cannot simulate all concurrency guarantees of the platform, and test reports express these separately. The length of the sequence and the running time have a budget, and the key actions in a few steps can better explain the root cause than an infinitely long random sequence.

Property Upgrade Based on Business Scope, Not Coverage Numbers

Expanding the maximum amount, adding more currencies, and allowing empty sort values in pagination all require updates to the underlying framework, while preserving the explanation of previously valid ranges. The overall coverage does not directly indicate whether key patterns appear; category statistics and the ability to detect intentional errors are more direct. Certain variations may be equivalent, but not necessarily indicating a test error. Review the business impact before deciding whether to add new properties.

The document will express the invariant in natural language, while the code will handle the executable search. Readers should first independently assess the validity of the invariant, fairness, and reasonableness, and then examine the framework’s syntax. When stating the method without executing samples, avoid fabricating the number of findings or relying on probability; successful random testing provides evidence within the scope, but is not a complete mathematical proof. The true outcome is a clear commitment and a provable counterexample.

Before upgrading the generator, save the category distribution and key counterexamples. After upgrading, check whether the valid samples still cover the original risks. If the amount is changed from non-divisible to divisible, it may disrupt the detection conditions. The framework and nature should jointly maintain the necessary prerequisites. “Minimum” does not necessarily mean the absolute minimum number of characters, but rather an effective input that can reliably explain failures.

The action model for concurrent systems must also distinguish between the planned order and the actual submission order. A purely sequential nature only proves that the rules are followed in that order, while true concurrency can be achieved by opening a window through controlled synchronization points and then comparing it with the allowed final state. Randomly generated sequential sequences cannot be considered as actual race coverage numbers; the two types of evidence should be reported separately.

Assessing and Developing Observation Skills

The following should be captured and provided as a concise counterexample:

  • Intentional introduction of remaining amounts resulting in loss
  • Unstable sorting
  • Incorrect duplicate deletion

The following should be verified:

  • The number of valid samples generated by the statistical test.
  • That rare branches are actually generated.

Finally, verify that the properties correspond to real-world business requirements, rather than simply satisfying the current implementation.

The results of the property tests are a set of executable invariants. Random input is just an amplifier; what truly matters are the rules that the team can clearly state as “rules that cannot be violated under any circumstances.”

References