CodingUnit TestsIntermediate30 minSaves 30 minutes

Stabilize Flaky Time-Dependent Tests in Your Codebase

For engineers battling CI failures, diagnose and refactor time-sensitive unit tests to eliminate flakiness and ensure reliable continuous integration.

This prompt guides engineers through diagnosing and stabilizing unit tests that fail intermittently due to time-dependent logic or timezone issues. It helps refactor tests to use deterministic time, ensuring consistent results and a more reliable CI pipeline.

READY-TO-USE PROMPT

Copy Prompt

prompt.txt
Role: Expert Test Engineer specializing in robust, deterministic unit testing.

Context:
You are presented with a unit test that exhibits flakiness, often failing in CI/CD environments but passing locally, or vice-versa. The primary suspect for this instability is its reliance on real-time, system clocks, or timezone configurations. You will be provided with the `{{flaky_test_code}}` and any `{{relevant_application_code}}` that the test interacts with. Your objective is to diagnose the root cause of the flakiness and provide a refactored, stable version of the test.

Task:
1.  **Analyze the provided code:** Examine `{{flaky_test_code}}` and `{{relevant_application_code}}` to pinpoint exactly where time-dependency is introduced and how it leads to non-deterministic behavior.
2.  **Identify the root cause:** Clearly articulate why the current test is flaky, specifically detailing the time-related factors (e.g., `datetime.now()`, `time.sleep()`, timezone assumptions, date formatting).
3.  **Propose a refactoring strategy:** Outline a plan to isolate the test from real-time dependencies. This typically involves:
    *   Using dependency injection to pass in a controllable time source.
    *   Patching or mocking time-related functions (e.g., `datetime.now`, `time.time`) to return predictable values.
    *   Refactoring application code to accept time as an argument rather than fetching it directly.
    *   Standardizing timezone handling within the test environment.
4.  **Implement the refactored test:** Provide the complete, stabilized unit test code. This new test must:
    *   Be deterministic, passing consistently regardless of when or where it's run.
    *   Maintain clear `arrange`, `act`, and `assert` sections.
    *   Utilize appropriate testing fixtures or setup methods.
    *   Include comments explaining key changes, especially around time manipulation.
    *   Address any identified coverage gaps in the original test.

Constraints:
*   The refactored test must be written in the same programming language as the original `{{flaky_test_code}}`.
*   Prioritize readability and maintainability in the refactored test.
*   Avoid introducing new external dependencies unless absolutely necessary for stabilization, and if so, justify them.
*   The solution should focus on unit testing principles, isolating the component under test as much as possible.
*   Assume standard testing frameworks for the given language (e.g., Pytest for Python, JUnit for Java, Jest for JavaScript).

Output:
Provide your response in the following structure:

1.  **Root Cause Analysis:**
    *   Detailed explanation of why the original test is flaky, referencing specific lines or patterns in the provided code.
    *   Identification of all time-dependent elements.

2.  **Refactoring Strategy:**
    *   A concise plan outlining the approach to stabilize the test.

3.  **Refactored Test Code:**
    *   The complete, stabilized unit test file(s).
    *   Include necessary imports, fixtures, and clear `arrange`/`act`/`assert` blocks.
    *   Add comments to highlight how time-dependency is handled.

4.  **Notes on Coverage Gaps (if any):**
    *   Briefly mention any areas of the application code that are still not adequately covered by the refactored test, or any edge cases related to time that might warrant additional tests.

Estimated results

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

Editor's note

Why this prompt matters

Flaky tests are a constant headache for engineering teams. They erode trust in the CI pipeline, leading to unnecessary re-runs, manual investigations, and slowed development cycles. Among the most common culprits are tests that inadvertently couple themselves to system time, timezones, or other temporal factors. These time-sensitive tests pass on one machine but fail on another, or worse, pass intermittently on the same machine, making debugging a frustrating experience.

This workflow is designed for engineers who regularly encounter these elusive CI failures. It provides a systematic approach to identifying and addressing the root causes of time-dependent flakiness. Instead of simply restarting builds and hoping for a different outcome, this method guides you through a diagnostic process, helping you pinpoint the exact temporal coupling in your test or application code.

By refactoring these tests to be deterministic and isolated from real-world time, you restore confidence in your test suite. A stable CI pipeline means faster feedback loops, fewer distractions for the team, and ultimately, more predictable software delivery. This isn't just about fixing a single test; it's about embedding a deeper understanding of test isolation and behavior-first principles into your development practices, ensuring your tests reliably validate code behavior, every time.

Anatomy

Prompt engineering breakdown

Role

Expert Test Engineer specializing in robust, deterministic unit testing.

Context

A unit test is exhibiting flakiness, primarily due to its reliance on real-time, system clocks, or timezone configurations. The model receives the flaky test code and any relevant application code it interacts with.

Goal

To diagnose the root cause of the flakiness and provide a refactored, stable version of the unit test, ensuring it passes consistently regardless of execution environment or time.

Constraints

The refactored test must be in the same programming language, prioritize readability and maintainability, avoid new external dependencies unless justified, adhere to unit testing principles, and assume standard testing frameworks. It must also include specific sections for analysis, strategy, and the refactored code.

Output format

The output is structured into four main sections: Root Cause Analysis (detailed explanation, time-dependent elements), Refactoring Strategy (concise plan), Refactored Test Code (complete, stabilized test file(s) with comments), and Notes on Coverage Gaps (if any).

Why this structure works

This prompt effectively guides the model by using role priming, which establishes the necessary expertise. Explicit constraints ensure the output adheres to best practices for test engineering and maintainability. The structured output format guarantees a comprehensive response, breaking down the complex task into manageable, actionable components, which helps in consistently generating high-quality, usable test code.

Pick your version

Prompt variations

BeginnerWorks with any model

When you need a straightforward fix for a simple time-dependent test, focusing on basic mocking techniques without deep architectural changes.

prompt.txt
As an experienced test developer, your task is to identify and fix a flaky unit test caused by time issues. I will provide `{{flaky_test_code}}` and some `{{application_code}}`.

First, tell me why the test is failing due to time (e.g., `datetime.now`, `time.sleep`).

Second, explain your simple plan to make it stable, usually by making time predictable (mocking).

Finally, give me the updated test code. It should run the same every time. Make sure it's easy to read and has comments where you changed how time works. The test should still follow the 'arrange, act, assert' pattern.
ProfessionalBest with claude

When a detailed, expert-level diagnosis and solution are required for complex time-dependent issues, including potential application code refactoring suggestions.

prompt.txt
Role: Expert Test Engineer specializing in robust, deterministic unit testing.

Context:
You are presented with a unit test that exhibits flakiness, often failing in CI/CD environments but passing locally, or vice-versa. The primary suspect for this instability is its reliance on real-time, system clocks, or timezone configurations. You will be provided with the `{{flaky_test_code}}` and any `{{relevant_application_code}}` that the test interacts with. Your objective is to diagnose the root cause of the flakiness and provide a refactored, stable version of the test.

Task:
1.  **Analyze the provided code:** Examine `{{flaky_test_code}}` and `{{relevant_application_code}}` to pinpoint exactly where time-dependency is introduced and how it leads to non-deterministic behavior.
2.  **Identify the root cause:** Clearly articulate why the current test is flaky, specifically detailing the time-related factors (e.g., `datetime.now()`, `time.sleep()`, timezone assumptions, date formatting).
3.  **Propose a refactoring strategy:** Outline a plan to isolate the test from real-time dependencies. This typically involves using dependency injection, patching time-related functions, or refactoring application code.
4.  **Implement the refactored test:** Provide the complete, stabilized unit test code. This new test must be deterministic, maintain clear `arrange`, `act`, and `assert` sections, utilize appropriate fixtures, and include comments explaining key changes.

Constraints:
*   The refactored test must be written in the same programming language as the original `{{flaky_test_code}}`.
*   Prioritize readability and maintainability. Avoid new external dependencies unless justified.
*   Focus on unit testing principles, isolating the component under test.

Output:
Provide your response in the following structure:
1.  **Root Cause Analysis:**
2.  **Refactoring Strategy:**
3.  **Refactored Test Code:**
4.  **Notes on Coverage Gaps (if any):**
Short VersionWorks with any model

For quick identification and resolution of common time-based flakiness, prioritizing a concise output over extensive explanation.

prompt.txt
Fix this flaky unit test. It fails due to real-time dependencies, such as `datetime.now()` or timezone issues. Provide the `{{flaky_test_code}}` and any `{{relevant_application_code}}`. Identify the exact time-related problem and propose a solution, typically involving mocking or injecting a fixed time source. Then, deliver the fully refactored, stable test code. The new test must be deterministic, follow `arrange`/`act`/`assert`, and include comments for time-related changes. Focus on a direct, actionable solution.
EnterpriseBest with gemini

In organizations with strict compliance, auditing, or team best practices, where documentation of risk, adherence to standards, and impact assessment are critical.

prompt.txt
Role: Senior Test Architect with expertise in compliance and deterministic testing for enterprise systems.

Context:
A critical unit test, `{{flaky_test_code}}`, is causing CI/CD pipeline instability, impacting deployment reliability and increasing operational risk. This flakiness is attributed to uncontrolled real-time or timezone dependencies within `{{relevant_application_code}}`. Your objective is to deliver a thoroughly stabilized test, alongside comprehensive documentation for auditability.

Task:
1.  **Compliance-Driven Root Cause Analysis:** Detail the non-deterministic behavior, linking specific time dependencies (e.g., system clock calls, implicit timezone assumptions) to potential compliance risks or operational failures.
2.  **Standardized Refactoring Strategy:** Propose a strategy that aligns with team best practices (e.g., dependency injection, standardized time mocking frameworks) and mitigates future flakiness. Justify any proposed changes to application code.
3.  **Auditable Refactored Test Implementation:** Provide the complete, stabilized unit test. It must be deterministic, clearly structured with `arrange`/`act`/`assert`, use approved fixtures, and include exhaustive comments detailing all time-related changes and their rationale for traceability.
4.  **Risk & Coverage Assessment:** Identify any remaining test coverage gaps or potential edge cases related to time and discuss the residual risk, recommending further actions if necessary.

Constraints:
*   Adhere to enterprise coding standards and testing frameworks.
*   All changes must be justifiable for future audits and team reviews.
*   Prioritize maintainability and long-term stability over expediency.

Output:
1.  **Root Cause & Risk Analysis:**
2.  **Refactoring Strategy (Enterprise Standard):**
3.  **Refactored Test Code (Auditable):**
4.  **Coverage Gaps & Residual Risk Notes:**

What you'll get

Expected output

1. Analyze the provided code

`relevant_application_code.py` ```python import datetime

def create_log_entry(message): return f"{datetime.datetime.now()}: {message}" ```

`flaky_test_code.py` ```python import unittest from datetime import datetime from relevant_application_code import create_log_entry

class TestLogEntry(unittest.TestCase): def test_log_entry_timestamp(self): message = "System operational" entry = create_log_entry(message)

# This assertion is problematic. expected_prefix = datetime.now().strftime("%Y-%m-%d %H:%M:%S") self.assertTrue(entry.startswith(expected_prefix)) self.assertIn(message, entry) ```

2. Identify the root cause

The test test_log_entry_timestamp is flaky because it relies on datetime.datetime.now() being called twice and returning the *exact* same value, or at least values that produce the same strftime("%Y-%m-%d %H:%M:%S") string. One call occurs within create_log_entry in the application code, and the second occurs within the test's expected_prefix calculation. Due to the non-deterministic nature of system clocks and potential microsecond differences in execution time, these two calls can easily fall on different seconds, leading to a mismatch in the expected_prefix and subsequent test failure. This is especially prevalent in CI environments with variable execution speeds.

3. Propose a refactoring strategy

The strategy is to isolate the create_log_entry function from real-time clock dependencies during testing. This will involve using a mocking framework to control the datetime.datetime.now() function. By patching datetime.datetime within the relevant_application_code module, we can force datetime.datetime.now() to return a fixed, predictable datetime object. This ensures that both the application code and the test's assertion operate on the same, controlled timestamp, making the test deterministic.

4. Implement the refactored test

```python import unittest from unittest.mock import patch from datetime import datetime from relevant_application_code import create_log_entry

class TestLogEntryRefactored(unittest.TestCase): @patch('relevant_application_code.datetime') def test_log_entry_timestamp_stable(self, mock_datetime): # Arrange # Define a fixed, predictable time for the test. fixed_time = datetime(2023, 1, 15, 10, 30, 0, 123456)

# Configure the mock datetime.datetime.now() to return our fixed time. mock_datetime.datetime.now.return_value = fixed_time

# Ensure other datetime methods (like constructor) still work if needed. # This line is crucial if the application code uses datetime.datetime() constructor # in addition to datetime.datetime.now(). mock_datetime.datetime.side_effect = lambda *args, **kw: datetime(*args, **kw)

message = "System operational"

# Act # create_log_entry now uses the fixed_time due to the patch. entry = create_log_entry(message)

# Assert # The expected prefix now directly matches the fixed_time. expected_prefix = fixed_time.strftime("%Y-%m-%d %H:%M:%S") self.assertTrue(entry.startswith(expected_prefix)) self.assertIn(message, entry)

# Example of an additional test case for robustness @patch('relevant_application_code.datetime') def test_log_entry_different_message(self, mock_datetime): fixed_time = datetime(2024, 2, 20, 14, 0, 0) mock_datetime.datetime.now.return_value = fixed_time mock_datetime.datetime.side_effect = lambda *args, **kw: datetime(*args, **kw)

message = "Another important event" entry = create_log_entry(message)

expected_prefix = fixed_time.strftime("%Y-%m-%d %H:%M:%S") self.assertTrue(entry.startswith(expected_prefix)) self.assertIn(message, entry) ```

Under the hood

Why this prompt works

This prompt is effective because it leverages several key prompt engineering techniques to address the complex problem of flaky time-dependent tests. The "Role: Expert Test Engineer" instruction immediately primes the model to adopt a specialist persona, ensuring the output is technically accurate and actionable. This role-playing establishes an authoritative voice for diagnosis and solution generation. The detailed, numbered task list (Analyze, Identify, Propose, Implement) acts as a step-by-step guide, a form of chain-of-thought prompting. This structured approach ensures a thorough diagnosis of the flakiness, followed by a well-reasoned refactoring strategy, rather than just a quick fix. By explicitly asking for the root cause and a refactoring plan before implementation, the prompt guides the model towards a deeper understanding of the problem. Furthermore, the prompt suggests specific techniques like dependency injection and mocking time functions, directing the model towards industry best practices for unit test stabilization. Finally, the clear constraints and requirements for the refactored test, such as determinism, AAA structure, and comments, ensure the generated code is high-quality, readable, and directly usable by an engineer. This comprehensive structure leads to reliable, production-ready solutions for test flakiness.

Model fit

Best AI models for this prompt

Claude

Claude models excel at understanding complex code logic and providing detailed, human-readable explanations. Its ability to follow multi-step instructions makes it effective for diagnosing subtle time-dependent issues and outlining a clear refactoring strategy. While strong in analysis, verify its proposed code changes for idiomatic correctness in specific language versions. See the full Claude hub for deeper guidance.

ChatGPT

ChatGPT models are proficient at code generation and refactoring across various languages. They can quickly identify common patterns of time-dependent flakiness and suggest practical solutions using mocking or dependency injection. Review the generated code carefully, as it may occasionally produce less optimal or slightly verbose solutions that require minor adjustments. See the full ChatGPT hub for deeper guidance.

Gemini

Gemini models demonstrate strong capabilities in code comprehension and generating targeted fixes. They are particularly good at identifying specific API calls that introduce time-dependency and suggesting precise mocking strategies. Ensure the generated code adheres to the exact syntax and best practices of your project's testing framework, as some nuances might be missed. See the full Gemini hub for deeper guidance.

When to use

  • When your CI/CD pipeline exhibits intermittent failures that seem tied to execution timing or environment.
  • When local tests pass consistently, but the same tests fail unpredictably on different machines or CI agents.
  • To isolate tests that rely on datetime.now(), time.sleep(), or other system time functions.
  • When tests involving date parsing, formatting, or timezone conversions produce inconsistent results.
  • For stabilizing tests that interact with external services sensitive to current time, ensuring predictable responses.

When not to use

  • When the test flakiness is demonstrably caused by factors other than time or timezone, such as race conditions in concurrent code.
  • If the core functionality being tested is the system clock itself or a time-syncing mechanism.
  • For integration tests where interaction with real external time sources is an explicit requirement.
  • If the application under test is inherently non-deterministic and the test aims to observe that behavior.

Get more from it

Pro tips

  • 1

    Provide a minimal, reproducible example of both the flaky test and its application code dependency to avoid misdiagnosis.

  • 2

    Clearly state the programming language and testing framework to ensure the generated solution is directly applicable and idiomatic.

  • 3

    Detail any observed patterns of flakiness (e.g., "fails 1 in 10 runs, always in the afternoon") to help pinpoint subtle timing windows.

  • 4

    Consider refactoring application code to accept a time provider as an argument, making it inherently more testable than relying solely on mocking.

  • 5

    Specify the expected behavior or desired outcome of the test in addition to the current flaky state, guiding the stabilization process.

  • 6

    Include relevant environment variables or configuration snippets if timezone settings are determined externally, preventing overlooked factors.

Don't ship this

Common mistakes

  • Submitting only the test code without the application code it exercises.

    Fix — Always include the specific application code under test to allow for a complete and accurate diagnosis of time dependencies.

  • Omitting details about the testing environment or CI setup where flakiness occurs.

    Fix — Describe *where* the test fails (e.g., "on Jenkins with UTC timezone") to help identify environmental time differences.

  • Expecting a fix for flakiness unrelated to time or timezone issues.

    Fix — Confirm the root cause of the flakiness is genuinely time-related before using this prompt for diagnosis and stabilization.

  • Over-mocking the application under test, leading to unrealistic test scenarios.

    Fix — Target only the time-dependent components for mocking; avoid unnecessarily mocking stable, deterministic logic.

  • Failing to specify the exact programming language and testing framework in use.

    Fix — Clearly state the language (e.g., Java) and framework (e.g., JUnit) for precise, executable code solutions.

  • Ignoring potential edge cases like daylight saving changes or leap years in time-dependent logic.

    Fix — Mention these specific time scenarios as potential failure modes to ensure the refactored test accounts for them.

People also ask

Frequently asked questions

Q.Can this prompt handle tests that involve asynchronous operations with inherent time delays?

Yes, the prompt is designed to address time.sleep() or similar delays by mocking the underlying time source. This allows you to control the passage of time deterministically within your test, making asynchronous waits predictable.

Q.What if my application code is tightly coupled to `datetime.now()` and refactoring for dependency injection is difficult?

The prompt prioritizes mocking time-related functions like datetime.now() as a primary strategy. This approach stabilizes tests by providing predictable time values without requiring extensive changes to your core application logic.

Q.Will the refactored test use a specific mocking library, or is it generic?

The solution will utilize the standard mocking capabilities of the specified testing framework (e.g., unittest.mock.patch for Python, Mockito for Java). If an external library is needed, its justification will be provided.

Q.How much application code should I provide for the `relevant_application_code` input?

Provide only the minimal code necessary to demonstrate the interaction with the flaky test. This usually means the specific function(s) or class(es) that the test calls and whose behavior is time-dependent.

Q.Can this prompt assist with tests that fail due to different date formats or locales?

Yes, by standardizing timezone handling and potentially mocking date formatting functions or input, the prompt aims to eliminate locale-specific date format inconsistencies that lead to flakiness. Explicitly mention these issues.

Q.What if the observed flakiness is due to network latency, not strictly system time?

This prompt specifically targets time and timezone dependencies. While network latency can introduce timing issues, this prompt's core focus is on system time manipulation. A different diagnostic approach is needed for network-induced flakiness.

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