What if your test cases could be auto-generated by AI and automatically verified using Pytest?What if your test cases could be auto-generated by AI and automatically verified using Pytest?

Let AI Write Your Tests: How I Used OpenAI and Pytest to Auto-Generate API Test Cases

2025/12/03 15:10
3 min read
For feedback or concerns regarding this content, please contact us at [email protected]

AI seems to help almost every job in some way.

As SDET / QA, what if your test cases could be auto-generated by AI and automatically verified using Pytest ?

Hence, I recently tried integrating OpenAI with Pytest to automate API test generation. Here’s what I learned.

What You Need to Know and Prepare

Before diving in, here some tools and resources you’ll need:

  • OpenAI Python Library \n https://github.com/openai/openai-python

  • Pytest (Python testing framework) \n https://github.com/pytest-dev/pytest

  • API Under Test — FakeStoreAPI (Cart endpoint)

    https://fakestoreapi.com/docs#tag/Carts/operation/addCart

\

Setup Overview

Let OpenAI Build and Verify Basic Test Cases

We’ll start by asking OpenAI to generate simple API test cases using structured prompts. Then, we use Pytest to run and validate those cases against the real API.

\

  1. Install and Import Required Packages

$ pip install openai $ pip install pytest

https://gist.github.com/shyinlim/76bc4b8a37df414cccf29ea227ef6ab4?embedable=true

2. Define the Test Case Generator Function

We’ll create a function to send a prompt to OpenAI, instructing it to behave like a Senior SDET / QA and return structured API test cases in JSON format.

https://gist.github.com/shyinlim/7190ab613a342ce77c94bc906a55e258?embedable=true

3. Let OpenAI Build and Verify Basic Test Cases

Before defining the test function, we need to prepare a prompt that describes the API’s method, endpoint, and a sample of the request and response structure. This prompt will guide OpenAI to generate the test cases.

https://gist.github.com/shyinlim/1f6fe4fa0cc99edcff9e82504164ebfd?embedable=true

Once the prompt is ready, we define a test function that sends this information to OpenAI, retrieves the generated test cases, and runs them using Pytest.

https://gist.github.com/shyinlim/58334767807f41f76d5fbf73b4ac1f60?embedable=true

Okay, here’s a sample test cases of what OpenAI might return:

  • createcartwithvalidsingle_product
  • createcartwithmultipleproducts
  • createcartwithminimumvalid_values

\

\

Expand with Human-Designed Cases

While AI can quickly generate basic test cases. However, edge cases, business-specific logic, or tricky validation rules often still require human insight.

Use AI as a starting point, then build on it with your domain knowledge.

https://gist.github.com/shyinlim/709a54c3b9491a8f2f0b6aa171145211?embedable=true

Knowing When to Let AI Handle It

AI-generated test functions work best when:

  • API specs are clear and well-defined, including methods, parameters, and expected responses
  • Field validations are needed (data types, required fields, ranges).
  • Request / response flows are standard without complex business logic.
  • Need to quickly bootstrap test coverage, especially for repetitive or CRUD endpoints

You’ll still want to write tests manually when:

  • Business logic is complex or conditional, which AI may not fully understand.
  • Heavily DB-dependent tests, they often require manual setup and domain knowledge to ensure correctness.
  • Mocking or stubbing other services is needed, especially async or dependent ones.
  • Test results depend on side effects beyond response values, like logs or DB updates.
  • Security testing such as auth, permission, or injection checks is involved.

\

Final Thoughts

This experiment shows a great way to boost testing efficiency by combining OpenAI and Pytest.

It’s not about replacing SDET / QA Engineers, but about helping us get started faster, cover more ground, and focus on the tricky stuff.

The key takeaway ? \n The magic isn’t just in the AI, it’s in the prompt.

Good prompts don’t just show up by magic, they come from your mix of :

  • Testing experience
  • Testing techniques
  • Testing mindset
  • Communication skills
  • Product understanding

\ \ Here’s my GitHub repo showing a straightforward example:

https://github.com/shyinlim/openaiwithpytestsimpleversion?source=postpage-----77e9cdb5b716---------------------------------------&embedable=true

\ Test smart, not hard. And, Happy Testing :)

Sh-Yin Lim (LinkedIn)

Market Opportunity
null Logo
null Price(null)
--
----
USD
null (null) Live Price Chart
Disclaimer: The articles reposted on this site are sourced from public platforms and are provided for informational purposes only. They do not necessarily reflect the views of MEXC. All rights remain with the original authors. If you believe any content infringes on third-party rights, please contact [email protected] for removal. MEXC makes no guarantees regarding the accuracy, completeness, or timeliness of the content and is not responsible for any actions taken based on the information provided. The content does not constitute financial, legal, or other professional advice, nor should it be considered a recommendation or endorsement by MEXC.

You May Also Like

Fed forecasts only one rate cut in 2026, a more conservative outlook than expected

Fed forecasts only one rate cut in 2026, a more conservative outlook than expected

The post Fed forecasts only one rate cut in 2026, a more conservative outlook than expected appeared on BitcoinEthereumNews.com. Federal Reserve Chairman Jerome Powell talks to reporters following the regular Federal Open Market Committee meetings at the Fed on July 30, 2025 in Washington, DC. Chip Somodevilla | Getty Images The Federal Reserve is projecting only one rate cut in 2026, fewer than expected, according to its median projection. The central bank’s so-called dot plot, which shows 19 individual members’ expectations anonymously, indicated a median estimate of 3.4% for the federal funds rate at the end of 2026. That compares to a median estimate of 3.6% for the end of this year following two expected cuts on top of Wednesday’s reduction. A single quarter-point reduction next year is significantly more conservative than current market pricing. Traders are currently pricing in at two to three more rate cuts next year, according to the CME Group’s FedWatch tool, updated shortly after the decision. The gauge uses prices on 30-day fed funds futures contracts to determine market-implied odds for rate moves. Here are the Fed’s latest targets from 19 FOMC members, both voters and nonvoters: Zoom In IconArrows pointing outwards The forecasts, however, showed a large difference of opinion with two voting members seeing as many as four cuts. Three officials penciled in three rate reductions next year. “Next year’s dot plot is a mosaic of different perspectives and is an accurate reflection of a confusing economic outlook, muddied by labor supply shifts, data measurement concerns, and government policy upheaval and uncertainty,” said Seema Shah, chief global strategist at Principal Asset Management. The central bank has two policy meetings left for the year, one in October and one in December. Economic projections from the Fed saw slightly faster economic growth in 2026 than was projected in June, while the outlook for inflation was updated modestly higher for next year. There’s a lot of uncertainty…
Share
BitcoinEthereumNews2025/09/18 02:59
The U.S. Department of Justice files civil forfeiture lawsuit for over $225 million in crypto fraud funds

The U.S. Department of Justice files civil forfeiture lawsuit for over $225 million in crypto fraud funds

PANews reported on June 18 that according to an official announcement, the U.S. Department of Justice filed a civil forfeiture lawsuit in the U.S. District Court for the District of
Share
PANews2025/06/18 23:59
Stellar’s XLM price climbs 7% as traders rotate into payment coins – can it go higher?

Stellar’s XLM price climbs 7% as traders rotate into payment coins – can it go higher?

Stellar’s XLM price jumps toward the top of its range as traders rotate into payment and remittance tokens amid rising volumes, stablecoin pilots, and CBDC tests
Share
Crypto.news2026/03/25 22:07